Creating an Object PHP

Once you have defined a class, you use the new statement to create an instance of the class, an object. If the definition of the class is the blueprint, the instance is the widget rolling off the assembly line. The new statement expects the name of a class and returns a new instance of that class. If a constructor with parameters has been declared, you may also follow the class name with parameters inside parentheses. Look for the line in Listing 6.1 that uses the new statement.

When you create an instance, memory is set aside for all the properties. Each instance has its own set of properties. However, the methods are shared by all instances of that class.

As you recall, PHP allows you to create variables without explicitly declaring the type. Objects are no different. You can create an object simply by using it in the proper context. That is, using the -> operator on a variable will make it an object. You can create as many properties as you wish on this new object just by referring to them. Unfortunately, you will not be able to attach methods to an object this way.

Another way to create an object is to change the type of an array. When an array becomes an object, all the elements indexed by strings become properties. Elements indexed by numbers will remain with the variable but will be inaccessible. If the variable later returns to being an array, the numbered elements will be accessible again. This is similar to what happens when an object is cast as an array. All properties will be available as array elements, but methods are not. When an object is created through casting or inference, it is of type stdClass.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

PHP Topics