Simplified code
<?php
class ClassA
{
public ClassB $b;
public string $c;
public function __construct()
{
$this->b = new ClassB($this);
$this->c = 'some text';
}
}
class ClassB {
}
$a = new ClassA();
// how to get $a->c from class B?
We need to get the value C of class A from class B called from class A (in that order).
It’s true that the best solution?
<?php
class ClassA
{
public ClassB $b;
public string $c;
public function __construct()
{
$this->b = new ClassB($this);
$this->c = 'some text';
}
}
class ClassB
{
public ClassA $a;
public function __construct($a)
{
$this->a = $a;
}
public function showAC()
{
return $this->a->c;
}
}
$a = new ClassA();
echo $a->b->showAC();
// some text
I used the code from the second example, but I think there must be a better way. Without passing $this on creation $this->b = new ClassB($this);
New contributor
Alexsander Alexandersson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.