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.

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

报告相同问题?

悬赏问题

  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱