dongzhong7299 2016-12-10 10:44
浏览 19
已采纳

使用匿名函数分配属性值

My class is like this:

<?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();

Property $example_property must be false until you call it, then, the first time it is called, I want to assign 1 to it. What's wrong with my code?

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

  • 写回答

1条回答 默认 最新

  • dongyi5425 2016-12-10 11:14
    关注

    I just tried to play a little bit with your code.

    To make it possible, you'll have to find out, whether your variable is a function (defined in your __construct) or the number set by this function

    <?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
    

    But anyway, I don't see any sense in doing this.

    The typical solution would be something like this:

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 利用单片机产生正弦信号,来测量差分放大电路放大倍数和共模放大倍数的思路和仿真
  • ¥66 定制开发肯德基自动化网站下单软件
  • ¥20 vscode虚拟环境依赖包未安装
  • ¥15 odoo17关于owl开发js代码问题
  • ¥15 光纤中多普勒频移公式的推导
  • ¥15 怎么制作一个人脸识别门禁系统
  • ¥20 大华dss监控平台网络关闭登不进去
  • ¥15 请使用蚁群算法解决下列问题,并给出我完整的代码
  • ¥20 关于php录入完成后,批量更新数据库
  • ¥15 请教往复密封润滑问题