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 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?