PHP中的OOP - 带方法的变量导致对成员函数的致命调用

时间:2017-08-04 16:05:43

标签: php oop

我一直试图找到一个如何做到这一点的示例或提示,我不知道找到解决这个问题的方法。我有两个问题 - 这里是以下测试代码:

<?php
class TestClass {
    public $test;

    function __contruct(){

        // this fails:
        //$this->test = (object) array();

        // so does this:
        /*
        $this->test = new stdClass();
        $this->test->hello = function(){
            return 'hello world!';
        };
        */

        $this->test = array();
        $this->test['foo'] = 'bar';
        $this->test['buttons'] = array();
        $this->test['hello'] = function(){
            return 'hello world!';
        };
        $this->test['addButton'] = function($title,$url){
            // how do I call the class' addButton function and
            // pass a reference of the $test varaible so it gets updated?
        };

    }

    // this function would be used for multiple objects
    function addButton(&$obj,$title,$url){
        $obj['buttons'][] = array(
            'title' => $title,
            'url' => $url
        );
    }
}

$myTestClass = new TestClass;
// this results in:
// Fatal error: Call to a member function hello() on null
echo $myTestClass->test->hello();
?>

我很感激您提供的任何反馈

2 个答案:

答案 0 :(得分:2)

首先将UserA更改为UserManager<TUser>

然后确保调用此函数__contruct

调用__construct假设您的班级echo $myTestClass->test['hello']();中有一个名为$myTestClass->test->hello();的方法,您不会

试试这个,它有效

hello()

答案 1 :(得分:0)

你拼写__construct错了。您需要function __contruct() {}。然后将调用构造函数,您将看到结果。由于您正在访问阵列,因此您需要在访问时使用[]语法。所以echo $myTestClass->test['hello']();

此外,你可以这样做:

$self = $this;
$this->test['addButton'] = function($title,$url) use ($self) {
    // how do I call the class' addButton function and
    // pass a reference of the $test varaible so it gets updated?
    $self->addButton($self, $title, $url);
};