【问题标题】:Why this $class works and $this->class not?为什么这个 $class 有效而 $this->class 无效?
【发布时间】:2016-05-16 10:13:04
【问题描述】:

我有两节课

class A {

   // Do some stuff here!

}

class B {

   public $class = 'A';

   public function getClass(){

      //Case 1
      $class = $this->class;
      return new $class(); //work

      //Case 2
      return new $this->class(); //NOT work
      //or to be precise something like this
      return new {$this->class}(); 

   }

   // Do some other stuff here!

}

为什么将类属性传递给 var 工作并直接访问不是,就像您在上面的类中看到的那样,Case 1 vs. Case 2

【问题讨论】:

  • 因为return new $this->class(); 含糊不清....你是说return new ($this->class()); 还是return new ($this)->class();? (添加括号以显示潜在的歧义)
  • 仅供参考:上面的确切代码在我的 Linux 服务器和 PHP 5.6.21 中完美运行。
  • 它对我有用,正如您对 php 5.6 和 7 所期望的那样
  • 在您的声明中放置大括号(根据您的编辑)return new {$this->class}(); 消除歧义

标签: php class oop instance


【解决方案1】:

原因是

$class = $this->class;
return new $class();

这里$class 将包含值“A”。因此,当您调用 new $class() 时,它将获得“A”类

但是在

return new $this->class();

它将在“B”类中搜索函数class()。所以它不会起作用。

$this 用于表示当前类实例。 $this -> something() 将始终检查同一类中的函数 something()

【讨论】:

    【解决方案2】:

    是的,原因是你做错了,

    这就是你要做的,

    class A {
    
      public $class = 'A';
    
      function __construct() {
        # code...
      }
    
      public function getClass(){
        return $this;
      }
    
      public function instance () {
        return $this->class;
      }
    }
    

    获取对象/A

    $obj = new A();
    $new_obj = $obj->getClass();
    

    获取instance/$class的值,

    $inst = $obj->instance();
    

    $this 指类本身,

    【讨论】:

      【解决方案3】:

      似乎对我有用,如果我删除 '()' :)。

      return new $this->class; //Work just fine without parentheses
      

      注意:我使用的是 PHP 5.4.16

      【讨论】:

        猜你喜欢
        • 2011-08-12
        • 2016-10-05
        • 2011-11-25
        • 1970-01-01
        • 1970-01-01
        • 2019-01-03
        • 2015-08-22
        • 2013-12-17
        • 2019-02-10
        相关资源
        最近更新 更多