本文介绍了php类扩展,变量从其他扩展类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主类和两个扩展类:

I have a main class and two extended classes:

class Main {
    public $foo;
}

class A extends Main {
  public function setVar()
    {
      $foo = "test";
    }
}

class B extends Main {
  public function getVar()
    {
      return $this->foo;
    }
}

$A = new A;
$B = new B;

$A->setVar();

echo "result: ".$B->getVar();

但结果($ B-> getVar())保持为空。我在这里明显地缺少一些简单的东西......除此之外,这是在相关的子类中拆分长类的方法吗?

But result ($B->getVar()) stays empty. I am clearly missing something simple here... Besides that, is this the way to go splitting long classes up in relevant subclasses?

推荐答案

p>使用依赖注入(DI)在不同类实例之间共享Main实例而不是尝试使用继承的示例

Example of using Dependency Injection (DI) to share an instance of Main between to different class instances rather than trying to use inheritence

class Main {
    public $foo;
}

class A {

    protected $main;

  public function setVar($data)
    {
      $this->main->foo = $data;
    }

  public function __construct(Main $main)
    {
      $this->main = $main;
    }
}

class B extends Main {
    protected $main;

  public function getVar()
    {
      return $this->main->foo;
    }

  public function __construct(Main $main)
    {
      $this->main = $main;
    }
}

$M = new Main;
$A = new A($M);
$B = new B($M);

$A->setVar("test");

echo "result: ".$B->getVar();

这篇关于php类扩展,变量从其他扩展类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 18:20