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

报告相同问题?

悬赏问题

  • ¥25 C语言代码,大家帮帮我
  • ¥15 请问以下文字内容及对应编码是用了什么加密算法或压缩算法呢?
  • ¥50 关于#html5#的问题:H5页面用户手机返回的时候跳转到指定页面例如(语言-javascript)
  • ¥15 无法使用此凭据登录,因为你的域不可用,如何解决?(标签-Windows)
  • ¥15 yolov9的训练时间
  • ¥15 二叉树遍历没有报错但无法正常运行
  • ¥15 在linux系统下vscode运行robocup3d上场球员报错
  • ¥15 Python语言实验
  • ¥15 SAP HANA SQL 增加合计行
  • ¥20 用C#语言解决一个英文打字练习器,有偿