【发布时间】:2011-06-21 19:11:29
【问题描述】:
我有多个其他类需要的一组变量。我扩展了一个“不错”的 getter 函数(它猜测 var 名称并即时生成“set”/“get”函数)以与 setter 一起使用。
例子:
在接口/父级/任何东西中:public $name;
在加载“mySetterGetter”类的其他类中:$set_get = new mySetterGetter(); $set_get->get_name();。
遗憾的是,我不能在接口中使用变量,也不能扩展具有多个父类的类。还有其他方法可以加载这些“接口”/扩展 Set/Get 类吗?
我需要做的是:
// This should be my "interface" one
class myIntegerInterface
{
public $one;
public $two;
public $three;
}
// This should be my "interface" two
class myStringInterface
{
public $foo;
public $bar;
public $whatever;
}
// This is my setter/getter class/function, that needs to extend/implement different variable classes
class mySetterGetter implements myIntegerInterface, myStringInterface
{
/**
* Magic getter/setter method
* Guesses for a class variable & calls/fills it or throws an exception.
* Note: Already defined methods override this method.
*
* Original @author Miles Keaton <mileskeaton@gmail.com>
* on {@link http://www.php.net/manual/de/language.oop5.overloading.php#48440}
* The function was extended to also allow 'set' tasks/calls.
*
* @param (string) $val | Name of the property
* @param unknown_type $x | arguments the function can take
*/
function __call( $val, $x )
{
$_get = false;
// See if we're calling a getter method & try to guess the variable requested
if( substr( $val, 0, 4 ) == 'get_' )
{
$_get = true;
$varname = substr( $val, 4 );
}
elseif( substr( $val, 0, 3 ) == 'get' )
{
$_get = true;
$varname = substr( $val, 3 );
}
// See if we're calling a setter method & try to guess the variable requested
if( substr( $val, 0, 4 ) == 'set_' )
{
$varname = substr( $val, 4 );
}
elseif( substr( $val, 0, 3 ) == 'set' )
{
$varname = substr( $val, 3 );
}
if ( ! isset( $varname ) )
return new Exception( "The method {$val} doesn't exist" );
// Now see if that variable exists:
foreach( $this as $class_var => $class_var_value )
{
if ( strtolower( $class_var ) == strtolower( $varname ) )
{
// GET
if ( $_get )
{
return $this->class_var_value;
}
// SET
else
{
return $this->class_var_value = $x;
}
}
}
return false;
}
}
【问题讨论】:
-
我想知道,你为什么需要那种魔法?如果您需要自定义 setter 和 getter,为什么不直接通过属性工作并在稍后阶段引入 __get 和 __set?
-
整个结构是在一个更大的结构中实现的。我有一个加载器/扩展器类、数据库处理等等。整个构造当前设置为处理不同的场景(创建页面、可拖动框、表格和表单字段。唯一的区别是 a)我需要的基本值和 b)我为不同场景调用的构造函数类。因此,不为不同的场景编写 set_/get_ 函数会让我的生活更轻松,而是让这由 __call 方法处理,并且只在单个封装文件/类中定义变量。