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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测