【问题标题】:Assigning a function's result to a variable within a PHP class? OOP Weirdness将函数的结果分配给 PHP 类中的变量? OOP 怪异
【发布时间】:2011-04-03 12:10:33
【问题描述】:

我知道您可以将函数的返回值分配给变量并使用它,如下所示:

function standardModel()
{
    return "Higgs Boson";   
}

$nextBigThing = standardModel();

echo $nextBigThing;

所以有人请告诉我为什么以下不起作用?还是只是还没有实施?我错过了什么吗?

class standardModel
{
    private function nextBigThing()
    {
        return "Higgs Boson";   
    }

    public $nextBigThing = $this->nextBigThing();   
}

$standardModel = new standardModel;

echo $standardModel->nextBigThing; // get var, not the function directly

我知道我可以这样做:

class standardModel
{
    // Public instead of private
    public function nextBigThing()
    {
        return "Higgs Boson";   
    }
}

$standardModel = new standardModel;

echo $standardModel->nextBigThing(); // Call to the function itself

但在我的项目中,存储在类中的所有信息都是预定义的公共变量,除了其中一个需要在运行时计算值。

我希望它保持一致,因此我和使用此项目的任何其他开发人员都必须记住,一个值必须是函数调用,而不是 var 调用。

不过不用担心我的项目,我主要只是想知道为什么 PHP 的解释器内部不一致?

显然,这些例子是为了简化事情而编造的。请不要质疑“为什么”我需要把所说的功能放在课堂上。我不需要关于正确 OOP 的课程,这只是一个概念证明。谢谢!

【问题讨论】:

    标签: php oop class variables function


    【解决方案1】:
    public $nextBigThing = $this->nextBigThing();   
    

    您只能initialize class members with constant values。 IE。此时您不能使用函数或任何类型的表达式。此外,此时该类甚至还没有完全加载,因此即使它被允许,您也可能无法在它仍在构建时调用它自己的函数。

    这样做:

    class standardModel {
    
        public $nextBigThing = null;
    
        public function __construct() {
            $this->nextBigThing = $this->nextBigThing();
        }
    
        private function nextBigThing() {
            return "Higgs Boson";   
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      您不能将默认值分配给这样的属性,除非该值是常量数据类型(例如字符串、整数...等)。本质上处理代码的任何内容(例如函数,甚至 $_SESSION 值)都不能作为默认值分配给属性。你可以做的是在构造函数中为属性分配你想要的任何值。

      class test {
          private $test_priv_prop;
      
          public function __construct(){
              $this->test_priv_prop = $this->test_method();
          }
      
          public function test_method(){
              return "some value";
          }
      }
      

      【讨论】:

        【解决方案3】:
        class standardModel
        {
        // Public instead of private
        public function nextBigThing()
        {
            return "Higgs Boson";   
        }
        }
        
        $standardModel = new standardModel(); // corection
        
        echo $standardModel->nextBigThing(); 
        

        【讨论】:

          猜你喜欢
          • 2020-10-05
          • 1970-01-01
          • 1970-01-01
          • 2010-10-02
          • 2014-07-16
          • 2013-11-12
          • 1970-01-01
          • 1970-01-01
          • 2019-01-07
          相关资源
          最近更新 更多