PHP Object Oriented Programming - Introduction

PHP

In this tutorial we will learn about Object Oriented Programming in PHP.

What is Object Oriented Programming?

Object Oriented Programming (OOP) is a programming paradigm based on objects having attributes and methods which work on that attributes.

Following are some of the OOP langauges: C++, Java, PHP, C#, Objective-C, Swift.

What is a class?

In OOP, a class is a blueprint of an object.

For example, a real world car has some characteristics and behavious. Some of the characteristics of a car are the color, top speed, weight, number of seats, manufacturer, number plate etc. And some of the behaviours of a car are that it can accelerate, apply break, play radio, sound the horn etc.

To express the car in OOP we use class. All the characteristics of the car becomes the attribute of the class and all the behaviour of the car becomes the methods.

What is an object?

In simple terms, an object is an instance of a class. That is, if a class is a blueprint of a building then the object is the actual building.

What is a property of a class?

In OOP, the attributes of a class are also known as properties of the class. They are the variables of the class.

For example, color of the car is the characteristics. So, in OOP it becomes the attribute or property of the class car.

What is a method of a class?

In OOP, the behaviours of a class are defined by methods. They are the functions of the class but we call them methods.

For example, accelerate is one of the behaviour of the car. So, in OOP it becomes the method of the class car.

How to create a class?

We use the class keyword to create a class in PHP followed by the name of the class.

A common programming convention is to start the name of a class with capital letter.

In the following code we are creating a class "Student".

class Student {
	
}

How to create an object of a class?

To create an object of the Student class, the one we created above, we use the new keyword.

$stdObj = new Student();

When we create an object of a class we call it an instance of the class.

We can't do much with the above object at the moment because the class Student has no properties and methods.

So, lets explore more about class properties.

Property and its scope

Property of a class is like a variable and it has some scope to control its accessibility.

Each property of a class can have three scopes - public, private and protected.

Public property

We use the public keyword to create a public property for a class.

This type of properties are easy accessible from any parts of the code both inside and outside of the class. We can read and modify public properties from any part of the script.

class Student {
	public $name;
}

In the above code we created a public property $name for the Student class.

Private property

We use the private keyword to create a private property for a class.

Private properties are only accessible inside the class by the methods created inside that class.

class Student {
	public $name;
	private $address;
}

In the above code we created a private property $address for the Student class.

Protected property

We use the protected keyword to create a protected property.

Protected properties are accessible from inside the class (like private property) and any class that inherits from the class.

We will learn more about inheritance in later tutorial.

class Student {
	public $name;
	private $address;
	protected $studentid;
}

In the above code we created a protected property $studentid for the Student class.

Accessing class properties using object

We can only access public property using class object. Both private and protected properties when accessed via object will return fatal error.

To access a public property using object we use the arrow symbol (->).

class Student {
	public $name;
	private $address;
	protected $studentid;
}

$stdObj = new Student();

//accessing public property
$stdObj->name = "Alice";

//this will give error
$stdObj->address = "123 Street";

//this will also give error
$stdObj->studentid = "s01";

Static property

Like static variable we can also created a static property for a class using the static keyword before the property name.

Static properties are independent of any object of a class and can be accessed using just the class name followed by :: operator.

class Sample {
	public static $code = 10;
}

echo Sample::$code;		//this will print 10

Constant of a class

We use the const keyword to create class constant. As the name suggests their value never changes.

We generally follow the convention of using all capital letters when naming a constant.

Like a static property we can access a class constant using the class name followed by the :: operator.

class Sample {
	const CODE = 10;
}

echo Sample::CODE;		//this will print 10

Method and its scope

We create class method using the function keyword. The scope of a method controls its accessibility.

Each method of a class can have three scopes - public, private and protected.

If no scope for the method is set then it is considered to be public.

Public method

We use the public keyword to create a public function.

Public method of a class is accessible from anywhere both inside and outside the class.

class Sample {
	public function foo() {

	}
}

Private method

We use the private keyword to create a private method for a class.

A private method is only accessible from other methods of the same class.

class Sample {
	private function foo() {

	}
}

Protected method

We use the protected keyword to create a protected method for a class.

A protected method is only accessible from other methods of the same class or in the class that inherts from the class.

class Sample {
	protected function foo() {

	}
}

Call methods of a class using object

We use the -> symbole to call a method of a class using the object. In the following example we have a class Sample having a public method foo(). We will create an object $obj and call the method that will display "Hello World!".

class Sample {
	
	public function foo() {
		printf("Hello World!");
	}
}

$obj = new Sample();

$obj->foo();		//this will print "Hello World!"

If we try to call a private or protected method using object of the class we will get fatal error.

class Sample {
	
	private function disp1() {
		printf("Hello World!");
	}

	protected function disp2() {
		printf("Hello World!");
	}
}

$obj = new Sample();

$obj->disp1();		//this will give error
$obj->disp2();		//this will give error

Passing argument to a method

In the following example we will pass an argument to a public method foo() of a class Sample.

class Sample {
	
	public function foo($text) {
		printf("Hello %s!", $text);
	}
}

$obj = new Sample();

$obj->foo("Yusuf");		//this will print "Hello Yusuf!"

Method returning value

In the following example the public method foo() of the class Sample return a value when called.

class Sample {
	
	public function foo($text) {
		return sprintf("Hello %s!", $text);
	}
}

$obj = new Sample();

$str = $obj->foo("Yusuf");		//this will return "Hello Yusuf!"

printf($str);		//this will print "Hello Yusuf!"

The $this variable

To access an object's properties and methods from within the methods of the same object we use the $this special variable.

Access a property from a method

In the following example we have a private property $name of a class Student. We are going to set the value and then display it using two public methods of the class.

//define the class
class Sample {
	
	//property
	private $name;

	//methods

	public function setName($val) {

		$this->name = $val;		//this will set the value of property $name

	}

	public function displayName() {
		printf("Name = %s", $this->name);
	}

}

//instantiating the class Sample
$obj = new Sample();

//set the name
$obj->setName("Yusuf Shakeel");

//display the name
$obj->displayName();

Calling methods from inside the class

To call a method from another method that belong to a class we use the $this special variable.

In the following example we define a class Sample which has a private property $name. We use the public method setName() to set the value of the $name. Then from inside this method we call the private method displayName().

//define the class
class Sample {
	
	//property
	private $name;

	//methods

	public function setName($val) {

		$this->name = $val;		//this will set the value of property $name

		$this->displayName();	//calling the private method to display $name

	}

	private function displayName() {
		printf("Name = %s", $this->name);
	}

}

//instantiating the class Sample
$obj = new Sample();

//set the name and display
$obj->setName("Yusuf Shakeel");

Static method

We use the static keyword to create a static method. Just like a static property, a static method can be accessed using the class name followed by the :: operator.

class Sample {
	public static function foo() {
		printf("Hello World!");
	}
}

echo Sample::foo();	//calling the static method

Static methods are connected with the class and is shared by all the objects of that class.

Constructor

A constructor is a special method of a class that is called just after an object is created. We create constructor for a class using a method having a special name __construct(). Constructor is commonly used to initialise data.

class Sample {
	
	//property
	private $name;

	//constructor
	function __construct() {
		$this->name = "Not set";
	}

	//methods
	public function setName($val) {
		$this->name = $val;
	}

	public function getName() {
		return $this->name;
	}

}

//creating object
//this will also call the constructor
$obj = new Sample();

printf("Name = %s", $obj->getName());	//this will print "Name = Not set" because of __constructor call

//now set name
$obj->setName("Yusuf Shakeel");

printf("Name = %s", $obj->getName());	//this will print "Name = Yusuf Shakeel"

In the above code we have created a class Sample having private property $name and public methods like setName(), getName() and a constructor.

When we create an object i.e., instance of the class Sample, the constructor __construct() is called. It sets the value of the private property $name to "Not set" which is then printed. Next we set the value of $name and print it using the setName() and getName() methods.

Output

Name = Yusuf Shakeel

Destructor

A destructor is a special method of a class that is called just before an object is removed from memory. We create destructor for a class using a method having a special name __destruct(). Destructor is commonly used to perform cleanup like close of database connection, release of resources like file etc.

class Sample {
	
	//property
	private $name;

	//methods
	public function setName($val) {
		$this->name = $val;
	}

	public function getName() {
		return $this->name;
	}

	//destructor
	function __destruct() {
		printf("Destructor called...");
	}

}

//creating object
//this will also call the constructor
$obj = new Sample();

//now set name
$obj->setName("Yusuf Shakeel");

printf("Name = %s", $obj->getName());	//this will print "Name = Yusuf Shakeel"

In the above code we have created a class Sample having private property $name and public methods like setName(), getName() and a destructor.

We first create an object i.e., instance of the class Sample, then we set the value of $name and print it using the setName() and getName() methods. Before the object exits the destructor will be called.

Output

Name = Yusuf Shakeel
Destructor called...

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT