简体   繁体   中英

PHP Class with properties that has objects be accessible to these objects

I have a main php class such as this:

class MyClass {
    public $a;
    public $b;

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

is there a way the class which is stored in the $a ( SomeClass ) property can access the $b value which is actually a property which is stored in the class that initiated $a ( MyClass ) ?

You could do something like this:

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;

The output would be: some string

You can do something like this:

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM