Ad anonymous or lambda functions) 在任何情况下,我都会避免这些,因为如果稍后检查挂钩,您将不知道其名称,也不会得到非常神秘的输出。调试将是一件痛苦的事。
Ad your A) 该方法看起来不错,并提供了一个非常简单的API(+1)。
Ad @hakre A) 我在我的框架核心中使用了几乎相同的函数[1]——通过“set\\u”扩展;异常-动态设置和获取变量。这样,我只需要用一个子类来扩展这个类,这个子类看起来像一个“仅变量”接口(那些应该可用的接口)。这是一种很好的有组织的方法,它只在为单个任务服务的文件中保留内容。通过这样的方式,您可以避免为每个TAK编写特定的函数,例如“\\u replace”等。
[1] 代码-我一直都在运行它,所以你可以称之为“已测试-并正常工作”
/**
* 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 <[email protected]>
* on {@link http://www.php.net/manual/de/language.oop5.overloading.php#48440}
* The function was extended to also allow \'set\' tasks/calls and throws an exception.
*
* @param (string) $name | Name of the property
* @param unknown_type $args | arguments the function can take
*/
function __call( $name, $args )
{
$_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( sprintf( __( "The method %1$s doesn\'t exist" ), "<em>{$val}</em>" ) );
// 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};
}
// SET
else
{
return $this->{$class_var} = $x[0];
}
}
}
return false;
}