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 Properties

Properties are variables

Classes can have variables within it. Those variables are called properties. A property is a normal PHP variable which is in any data type (integer, string, array, object, etc).

In classes, before declaring a variable, we should add the visibility keyword to define where the variable is available. You will learn more about this later. For now, keep in mind that adding the public keyword in front of the variable will make the variable available everywhere.


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

As in the above example, we can declare any type of variable as a property. We can add default values for those properties. (Black is the default for $primaryColor) Also, note that the property $extra does not have a default value.

Remind the blueprint explanation. A blueprint can have default widths and heights in it. But, also some houses will need some additional features that are not defined in the blueprint. So, those additional features do not have a default value. But, they can be added to a house. (Ex: Having a pool)

Conclusion

In this chapter, we learned how to declare a property in a class.

In the next chapter, you will learn how to create objects from classes (different houses from a blueprint).

Facebook Twitter