具有属性的PHP类,这些对象可以访问这些对象

时间:2016-11-06 14:42:13

标签: php oop

我有一个主要的PHP类,如:

Application.EnableEvents = False

有一种方法,存储在class MyClass { public $a; public $b; function __construct() { $this->a = new \SomeClass(); $this->b = 'some string'; } } $a)属性中的类可以访问SomeClass值,该值实际上是存储在启动{的类中的属性{1}}($b)?

2 个答案:

答案 0 :(得分:1)

你可以这样做:

class MyClass {
    public $a;
    public $b;

    function __construct()
    {
      $this->a = new \SomeClass($this);
      $this->b = 'some string';
    }
}

class SomeClass {
    public $mc;

    function __construct(MyClass $mc)
    {
      $this->mc = $mc;
    }
}

$myClass = new MyClass();
echo $myClass->a->mc->b;

输出结果为:some string

答案 1 :(得分:0)

您可以这样做:

class MyClass {
    public $a;
    public $b;

    function __construct()
    {
       $this->b = 'some string';
       $this->a = new \SomeClass($this->b);
    }
}   

class SomeClass{

    function __construct($b) 
    {
        echo $b; // it will become a $this->b as given while creating new class in MyClass
    }
}