使用匿名函数分配属性值

时间:2016-12-10 10:44:36

标签: php oop

我的班级是这样的:

<?php

class ExampleClass{

    private $example_property = false;

    public function __construct(){
        $this->example_property = function() {
            $this->example_property = 1;
            return $this->example_property;
        };
    }

    public function get_example_property(){
        return $this->example_property; 
    }
}

$example = new ExampleClass();
echo $example->get_example_property();

属性$example_property必须为false,直到您调用它为止,然后,第一次调用它时,我想为其分配1。我的代码出了什么问题?

错误:Error Object of class Closure could not be converted to string on line number 20

1 个答案:

答案 0 :(得分:-1)

我只想尝试使用您的代码。

为了使其成为可能,您必须找出您的变量是否为函数(在__construct中定义)或此函数设置的数字

<?php

class ExampleClass{

    private $example_property = false;

    public function __construct(){
        $this->example_property = function() {
            $this->example_property = 1;
            return $this->example_property;
        };
    }

    public function get_example_property(){
        $func = $this->example_property;
        if(is_object($func) && get_class($func)=='Closure'){
            return $func();
        }
        return $func;
    }
}

$example = new ExampleClass();
echo $example->get_example_property(); //returning 1
echo $example->get_example_property(); //returning 1 again

但无论如何,我没有看到这样做的任何意义。

典型的解决方案是这样的:

class ExampleClass{

    private $example_property = false;

    public function __construct(){
        //usually initializing properties goes here.
        //$this->example_property = 1;
    }

    public function get_example_property(){
        // I think you want a value to be initialzed only if needed.
        // so then it can go here.
        if(!$this->example_property) {
            $this->example_property = 1; //initialize it, if needed
        }
        return $this->example_property;
    }
}

$example = new ExampleClass();
echo $example->get_example_property(); //returning 1
echo $example->get_example_property(); //returning 1 again