选择自定义类函数



我有一个自定义的PHP类,里面的方法很少。可以这样调用类方法:

<?php 
class someClass{
  function someMethod_somename_1(){
    echo 'somename1';       
  }
  function someMethod_somename_2(){
    echo 'somename2';   
  }
}
$obj = new someClass();
$methodName = $_GET['method_name'];
$obj->someMethod_{$methodName}(); //calling method
?>

的实际应用程序更复杂,但在这里我只提供这个简单的例子来获得主要思想。也许我可以在这里使用评估函数?

请不要使用 eval(),因为它在大多数情况下是邪恶的。

简单的字符串串联可帮助您:

$obj->{'someMethod_'.$methodName}();

您还应该验证用户输入!

$allowedMethodNames = array('someone_2', 'someone_1');
if (!in_array($methodName, $allowedMethodNames)) {
  // ERROR!
}
// Unrestricted access but don't call a non-existing method!
$reflClass = new ReflectionClass($obj);
if (!in_array('someMethod_'.$methodName, $reflClass->getMethods())) {
  // ERROR!
}
// You can also do this
$reflClass = new ReflectionClass($obj);
try {
  $reflClass->getMethod('someMethod_'.$methodName);
}
catch (ReflectionException $e) {
  // ERROR!
}
// You can also do this as others have mentioned
call_user_func(array($obj, 'someMethod_'.$methodName));

当然,采取这个:

$obj = new someClass();
$_GET['method_name'] = "somename_2";
$methodName = "someMethod_" . $_GET['method_name'];
//syntax 1
$obj->$methodName(); 
//alternatively, syntax 2
call_user_func(array($obj, $methodName));

在调用之前连接整个方法名称。

更新:

直接调用基于用户输入的方法从来都不是一个好主意。请考虑在之前对方法名称进行一些先前的验证。

你也可以利用php魔术方法,即__call()call_user_func_array()method_exists()相结合:

class someClass{
    public function __call($method, $args) {
         $fullMethod = 'someMethod_' . $method;
         $callback = array( $this, $fullMethod);
         if( method_exists( $this, $fullMethod)){
            return call_user_func_array( $callback, $args);
         }
         throw new Exception('Wrong method');
    }
    // ...
}

出于安全考虑,您可能希望创建一个包装器,该包装器将禁止调用其他方法,如下所示:

class CallWrapper {
    protected $_object = null;
    public function __construct($object){
        $this->_object = $object;
    }
    public function __call($method, $args) {
         $fullMethod = 'someMethod_' . $method;
         $callback = array( $this->_object, $fullMethod);
         if( method_exists( $this->_object, $fullMethod)){
            return call_user_func_array( $callback, $args);
         }
         throw new Exception('Wrong method');
    }
}

并将其用作:

$call = new CallWrapper( $obj);
$call->{$_GET['method_name']}(...);

或者也许创建execute方法,然后添加到someClass方法GetCallWrapper()

通过这种方式,您将获得将功能很好地封装到对象(类)中,而不必每次都复制它(如果您需要应用一些限制,即权限检查,这可能会派上用场)。

可以使用变量作为函数。例如,如果你有函数foo(),你可以有一些变量$func并调用它。下面是示例:

function foo() {
    echo "foo";
}
$func = 'foo';
$func();  

所以它应该像$obj->$func();一样工作

最新更新