doulianxing4015 2016-05-16 10:13
浏览 17
已采纳

为什么这个$ class工作,$ this-> class不行?

I have 2 classes

class A {

   // Do some stuff here!

}

and

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!

}

Why passing the class property to a var work and accessing directly NOT, like you see in the class above, Case 1 vs. Case 2 ?

  • 写回答

3条回答 默认 最新

  • dsizmmwnm56437180 2016-05-16 10:16
    关注

    The reason is

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

    Here $class will contain the value "A". So it will get class "A" when you call new $class()

    But in

    return new $this->class();
    

    It will search for a function class() inside the class "B". So it will not work.

    $this is for represent the current class instance. $this -> something() will always check for a function something() in the same class

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器