How to create and use objects
How to create an object
The syntax
$objectName = new ClassName(argumentList);
Create a Category
object $brass = new Category(4, 'Brass');
Create a Product object
$trumpet = new Product($brass, 'Getzen', 'Getzen 700SP Trumpet', 999.95);
How to access an object’s properties
The syntax for setting a public property value
$objectName->propertyName = value;
The syntax for getting a public property value
$objectName->propertyName;
Set a property
$trumpet->comment = 'Discontinued';
Get a property
How to call an object’s methods
The syntax
$objectName->methodName(argumentList);
Call the getFormattedPrice() method
$price = $trumpet->getFormattedPrice();
Object chaining
echo $trumpet->getCategory()->getName();
Description
- An object is an instance of a class. In other words, you can create more than one object from a single class. The process of creating an object from a class is sometimes called instantiation.
- To create an object, you code the new keyword followed by the name of the class and a set of parentheses. Inside the parentheses, you code the arguments for the constructor separated by commas.
- To access an object’s property, you code a reference to the object followed by the object access operator (->) and the name of the property.
- To call an object’s method, you code a reference to the object followed by the object access operator (->), the name of the method, and a set of parentheses. Inside the parentheses, you code the arguments for the method separated by commas.
- If a function or method returns an object, you can use the function or method call as a reference to the object and continue accessing the returned object’s properties and methods. This is called object chaining.
Back