Object Orientated PHP

5th Feb 19

I have enrolled onto a Object Orientated php course here I will highlight the areas I covered in the course.


A property can be either public, private or protected.  If a property of method of a class is defined as private then it can only be accessed by code that is inside the class.  If you attempt to access the private property or method outside the class, PHP will generate a fatal error.


A constant is a variable whose value cannot be changed once it has been assigned. 

class Dress   
		const SMALL= "Small";   
		const MEDIUM= "Medium";   
		const LARGE= "Large";   
		public $size;   
		public $color = "red";  // The color of the dress   
		Private $fabric = "linen"; // The fabric of the dress   
		Private $design = "Shift Dress"; // The design of the dress    
		Public function displayInfo(){   
			echo "The info about the dress.";   
			echo $this->color;   
			echo $this->fabric ;   
			echo $this->design;
			echo self::MEDIUM;
		private function helloWorld($number1, $number2){   
			return $number1 + $number2;   
$dressObj = new Dress();   
$dressObj->size = Dress::MEDIUM; 

Generally a constant is public and you can access the constant of the class with ::CONSTANT.  The constant is a value of the class not of the object (class instance).  If you want to access the constant within a class method you have to use the keyword self as $this references to the current object and self references to the class itself.

Data Encapsulation

Sometimes you don't want a property to be accessed from outside the class.  By setting a property of a class to private you can prevent that property being altered from outside the class.  Only the code within the class can access the private property.  To implement data encapsulation in your class you should make your properties private and provide public methods to access and change the private properties.

An example of Data encapsulation is below. You can pass an amount to alter the value of the account balance through the public deposit function and get the current balance through the getBalance method.  But you cannot set the property from outside the class.

	class Account   
			private $balance = 0; 
			public function deposit($amount){
				$this->balance += $amount;
				echo "Amount is been deposited in your account</br>";
				echo "New balance is ".$this->balance."</br>";
			public function getBalance(){
				return $this->balance;
			public function withdraw($amount){
				if($amount<= $this->balance){
					$this->balance -= $amount;
					echo "Amount is withdrawn";
					echo " remaining balance is ".$this->balance ;
					echo "Insufficient Balance";


	$accObj = new Account(); 
	echo $accObj->getBalance();


I have recently completed my apprenticeship.  I am currently building the API to a React JS site using Firebase.