doukunsan5553 2017-01-26 16:46
浏览 88
已采纳

PHP call_user_func_array实例内部实例

<?php

class foo 
{
    private $callVar = false;
    private $constructorVar = false;

    public function __construct()
    {
        $this->constructorVar = get_class($this);
    }

    public function __call($methodName, $arguments) 
    {
        $this->callVar = get_class($this);
        call_user_func_array(array($this, $methodName), $arguments);
    }

    protected function method($params)
    {
        echo('<br>Call var: '.$this->callVar.'<br>Constructor var: '.$this->constructorVar);
    }
}

class foo_sec extends foo
{
    protected function method($params)
    {
        echo 'First call: ';
        parent::method($params);
        echo '<br> Second call: ';
        $test = new foo_trd();
        $test->method('param2');
    }
}

class foo_trd extends foo
{

}

$m = new foo_sec();
$m->method('param');

?>

Gives this result:

First call:
Call var: foo_sec
Constructor var: foo_sec
Second call:
Call var:
Constructor var: foo_trd

This code should return the name of the instance that is currently running, but if the instance is inside another instance, the class name is empty in second one. Is this a PHP bug or some other issue I'm missing?

In other words, the Call var in the second call should be foo_trd - not empty.

  • 写回答

1条回答 默认 最新

  • duanqin4238 2017-01-26 17:29
    关注

    I believe you are experiencing something interesting to do with PHP and its inheritance visibility.

    In short when you are inside and instance of Foo you have access to the protected and private scope of all other instances that also extend Foo. As you are allowed to access the protected method() directly you will skip the call to __call().

    This can actually be useful when you want to make your constructor private and enforce factories.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?