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 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 Object Oriented ProgrammingPHP 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 Interfaces

PHP OOP Objects

If the class was a blueprint, objects are houses.

We can create multiple objects from a class. Sometimes these objects are called instances of the class.

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

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. You will learn more about this later.

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?

Facebook Twitter