Heya, Andy.
The code you provided should work, since undeclared class members are assumed to be public in PHP.
A slightly more sane-looking approach might look something like this:
-
class A
-
{
-
public $child;
-
-
public function __construct( $subVal )
-
{
-
$this->child = new B($subVal);
-
}
-
}
-
-
class B
-
{
-
public $id;
-
-
public function __construct( $id )
-
{
-
$this->id = $id;
-
}
-
}
-
-
$newVar = new A(666);
-
echo "B = {$newVar->child->id}";
-
Alternatively, you might want A to be a wrapper for B. In this case, you might consider using magic methods to make the child class accessible:
-
class A
-
{
-
protected $child;
-
-
public function __construct( $subVal )
-
{
-
$this->child = new B($subVal);
-
}
-
-
public function __get( $var )
-
{
-
if( isset($this->child->$var) )
-
{
-
return $this->child->$var;
-
}
-
else
-
{
-
return null;
-
}
-
}
-
}
-
-
class B
-
{
-
public $id;
-
-
public function __construct( $id )
-
{
-
$this->id = $id;
-
}
-
}
-
-
$newVar = new A(666);
-
echo "B = {$newVar->id}";
-
In the second example, PHP will look for A::$id, which doesn't exist, so it will instead call A::__get('id'), which will check to see if B::$id has been set.