class Car { public $make; public $model; public $year; function __construct($make, $model, $year) { $this->make = $make; $this->model = $model; $this->year = $year; } } $myCar = new Car("Honda", "Civic", 2015); echo $myCar->make; // Output: Honda
class Animal { public $name; public $sound; public $num_legs; function __construct($name, $sound, $num_legs) { $this->name = $name; $this->sound = $sound; $this->num_legs = $num_legs; } function speak() { echo $this->sound; } } // Using a package library to create objects using dependency injection $animalFactory = new \League\Container\Container(); $animalFactory->add("cat", function() { return new Animal("Cat", "Meow", 4); }); $myCat = $animalFactory->get("cat"); echo $myCat->num_legs; // Output: 4 $myCat->speak(); // Output: MeowIn this example, we have a class called Animal with properties name, sound, and num_legs. The __construct method initializes those properties when an object is created using the class. We also have a method called speak() that prints out the sound property. We use a package library called League\Container to create objects using dependency injection. We create a new container object called $animalFactory. We then add a new "cat" service to the container that returns a new Animal object with the parameters for name, sound, and num_legs passed in. We get the "cat" service from the container and assign it to the $myCat variable. We print out the num_legs property of the object using echo, and call the speak() method of the object. Package library: League\Container