PHP OOP

Các thuộc tính của OOP trong PHP

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).

Leave a Reply

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

Close