PHP TUTORIALPHP TutorialPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP CommentsPHP VariablesPHP Variable ScopePHP ConstantsPHP StringsPHP OutputPHP Data TypesPHP Type CastingPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP String FunctionsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP AdvancedPHP Include and RequirePHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms FinishingPHP OOPPHP OOP IntroductionPHP OOP ClassesPHP OOP PropertiesPHP OOP ObjectsPHP OOP MethodsPHP OOP $this KeywordPHP OOP Constructors and DestructorsPHP OOP VisibilityPHP OOP InheritancePHP OOP Abstract Classes and MethodsPHP OOP InterfacesPHP OOP TraitsPHP OOP ConstantsPHP OOP StaticPHP OOP NamespacesPHP OOP Autoloading

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.
Did you know? There's a #Group for you to get help on PHP.
Profile Picture
Supun Kavinda
I'm the Founder of Hyvor, Web Developer, Physics Lover, Flutist, and a Table Tennis Player.
My Websites