Calling class method from string stored as class member

微笑、不失礼 提交于 2019-12-24 17:39:28

问题


I am trying to call a method stored as $_auto, but it will not work.

<?php
    class Index {
        private $_auto;

        public function __construct() {
            $this->_auto = "index";
            $this->_auto();
        }

        public function index() {
            echo "index";
        }
    }

    $index = new Index();
?>

回答1:


You need to use call_user_func to do this:

call_user_func(array($this, $this->_auto));

Unfortunately PHP does not allow you to directly use property values as callables.

There is also a trick you could use to auto-invoke callables like this. I 'm not sure I would endorse it, but here it is. Add this implementation of __call to your class:

 public function __call($name, $args)
 {
     if (isset($this->$name) && is_callable($this->$name)) {
         return call_user_func_array($this->$name, $args);
     }
     else {
         throw new \Exception("No such callable $name!");
     }
 }

This will allow you to invoke callables, so you can call free functions:

 $this->_auto = 'phpinfo';
 $this->_auto();

And class methods:

 $this->_auto = array($this, 'index');
 $this->_auto();

And of course you can customize this behavior by tweaking what __call invokes.




回答2:


You code is trying to call a method called "_auto". To do what you are asking, you want to make the method name a php variable or something along the lines of what the other posters are saying.

class Foo {
    private function _auto() {
        echo "index";
    }

    public function callmethod($method) {
        $this->$method();
    }
}

$foo = new Foo();
$foo->callmethod('_auto');



回答3:


You don't have a method named _auto(), you only have a property named $_auto. If your intent is for a call to an undefined method to return a similarly named property if it exists, then you would need to write a __call() magic method to perform the logic of looking at a similarly named property and returning the value. So something like this would need to be added to your class:

public function __call($called_method, $arguments) {
    if(property_exists($this, $called_method)) {
        return $this->{$called_method};
    } else {
        throw new Exception('Illegal method call.');
    }
}



回答4:


I think you mistakenly defined "_auto" as a property?

Try using:

private function _auto(){}

Instead of

private $_auto


来源:https://stackoverflow.com/questions/14613210/calling-class-method-from-string-stored-as-class-member

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!