Objects within objects

Just like any other variable, objects can be used within other objects and are similarly accessed by using the small arrow -> access operator again.

 

This example instantiates a new (Display) object on line 23 that is assigned to the team property within the Rider object, it then assigns a value to the Display object's output property on line 27, and finally echo it back on line 30 to show the assignment has taken place:

<?php
	class Display {
		public $output;

		public function __construct() {
			echo "An object instance of the " . __CLASS__ . " class has been instantiated.<br>";
		}
	}

	class Rider {
		public $name;
		public $team;

		public function __construct() {
			echo "An object instance of the " . __CLASS__ . " class has been instantiated.<br>";
		}
	}

	$marquez = new Rider; //create a Rider object called marquez
	$marquez->name = "Marc Marquez"; //assign a value to its name property

	//now we assign a Display object to the team property
	$marquez->team = new Display;

	//next we assign a value to the output propertyy of the Display object,
	//whcih was assigned above to the team propetry of the Rider object
	$marquez->team->output = "My name is " . $marquez->name . " and I currently ride for Honda.";

	//just to be sure, here's the assigned output property
	echo $marquez->team->output ;
?>

Save & refresh browser:

An object instance of the Rider class has been instantiated.
An object instance of the Display class has been instantiated.
My name is Marc Marquez and I currently ride for Honda.

 

*note: the use of constructors, on lines 5 & 14,  is explained under the constructor magic method here

Leave a Reply