0

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) ?

3
  • 2
    You would have to pass the MyClass object to SomeClass by sending $this in the constructor or setting it after the object is created. You then would need to store MyClass as a property if you intend to use any where else in SomeClass after it is instantiated. Commented Nov 6, 2016 at 14:47
  • edit complete, i hope its clearer now. Commented Nov 6, 2016 at 14:47
  • @sebastianForsberg thats what I had in mind but I thought there might be a different way. Commented Nov 6, 2016 at 14:48

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Just so you know, if MyClass::$b ever changes it will not be reflected in the SomeClass object if done this way.
You are right :) so I think your solution might be better if he will create a new class where is not all variables set yet.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.