PHP OOP

PHP OOP Objects

PHP OOP Objects

If the class was a blueprint, objects are houses.

We can create multiple objects from a class. These objects are called instances of the class. This process is called instantiation.

Here’s our house class we wrote in the last chapters.


<?php
class House {
	public $primaryColor = 'black';
	public $secondaryColors = [
		'bathroom' => 'white',
		'bedroom' => 'light pink',
		'kitchen' => 'light blue'
	];
	public $hasPool = false;
	public $extra;
}

After the class declaration, you can create instances from it.


$myHouse = new House();
$friendHouse = new House();

Now each object is created having the default values of the class. You can check it by echoing the color of each object.


echo $myHouse -> primaryColor;
echo $friendHouse -> primaryColor;

Both would echo out the default value black.

-> is the object operator, which is used to access properties and methods of an object.

Tip: When accessing properties and methods of an object through the object operator, the dollar sign $ is not used with the property or method name.

It is considered as a bad practice to directly accessing properties from outside the class with ->. Getter methods are the recommendation. More details on later chapters.

You can also change the default property values of the class to make each house unique.


$myHouse -> primaryColor = 'red';
$friendHouse -> primaryColor = 'yellow';

Now, the color of my house is red and the color of my friend’s house is yellow.

What is the difference between classes and objects?

  • A class is a structure with default values and methods (Blueprint for a house).
  • Multiple objects can be created from a class. (Houses built from the blueprint)
  • Each object has all the properties and methods defined in the class, but they can have different property values.

Leave a Reply

Your email address will not be published. Required fields are marked *

Close