PHP

PHP class Example

In this example we are going to learn about classes in PHP, what they mean and how to use them.

  1. A computer with PHP 5.5 installed
  2. notepad++

1. Objects in PHP

A class is a collection of variables and functions working with these variables.
To effectively use classes we need to familiarize ourselves with the term objects. Classes can be useless without objects. To use a class we might have to create an instance of the class, the instance created is the object.

If we have a class named employee that holds details about each employee in an organization, to instantiate this class we simply do $worker=new employee(); . $worker is an object and an instance of employee.
You can think of a class as a blueprint or factory for constructing objects. A class specifies the characteristics that an object would have, but not necessarily the specific values of those characteristics.
 

1.2 Properties and Methods

In OOP(Object Oriented Programming) the characteristics of a class or object is known as it’s properties. Properties are variables (they have a name and value). Using an employee class as an example, the name of the employee is a property of the class or any object of the class.
Methods are simply the behavior of the class-actions associated with the class. Methods are somewhat like functions, the difference is that methods are associated with classes and objects.

1.3 Creating Classes

As you already imagined it is impossible to create an object without a class. To create a class in PHP you use the class keyword

employee.php

<?php

class employee{
public $name;


}
$worker=new employee();

?>

This is a simple class named employee, with property $name. To add a property to a class first we write the keyword public protected or private followed by the property name. The keyword we use to declare a property controls the scope or visibility of the property.

employee1.php

<?php
class employee{
public $name="John";


}
$worker=new employee();
echo $worker->name;
?>

To access an object property we write the name of the variable storing the object, followed by an arrow symbol composed a hyphen(-) and a greater than symbol (>), followed by the property name(the property name doesn’t have the $ sign before it).

employee2.php

<!DOCTYPE html> 
<html lang=en>
	<head>
	<style>
	html, body{
	width:100%;
	height:100%;
	margin:0%;
	font-family:"helvetica","verdana","calibri", "san serif";
	overflow:hidden;
	padding:0%;
	border:0%;
	}
	 
	</style>
	 		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/>
	
	<title>Employee Class</title>
	
	</head>
	<body>
<?php

class employee{
public $firstname="John";
public $hasbeenpaid=false; 
public $lastname="White";
private $salary=1000;
}
$worker=new employee();
if($worker->hasbeenpaid)
echo "$worker->firstname $worker->lastname has been paid $worker->salary";
else
echo "$worker->firstname $worker->lastname has not been paid $worker->salary";

?>
</body>
</html>

If this page is loaded In a browser, an error message is generated and displayed by PHP. The error message is shown because we tried to access a private property outside its class. A property declared private cannot be accessed from outside the class it was created($salary is private to the class employee) but a property declared public can be accessed from outside the class it was created.
How do we manipulate a private field in PHP? By simply creating a method that returns the value of the private field.

employee3.php

<!DOCTYPE html> 
<html lang=en>
	<head>
	<style>
	html, body{
	width:100%;
	height:100%;
	margin:0%;
	font-family:"helvetica","verdana","calibri", "san serif";
	overflow:hidden;
	padding:0%;
	border:0%;
	}
	 
	</style>
	 		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/>
	
	<title>Employee Class</title>
	
	</head>
	<body>
<?php

class employee{
public $firstname="John";
public $hasbeenpaid=false; 
public $lastname="White";
private $salary=1000;

public function getSalary(){
return $this->salary;

}
}
$worker=new employee();
if($worker->hasbeenpaid){
echo "$worker->firstname $worker->lastname has been paid" . $worker->getSalary();}
else{
echo "$worker->firstname $worker->lastname has not been paid" . $worker->getSalary();
}

?>
</body>
</html>


We created a method getSalary() which returns the value of the private field $salary

1.4 Static Properties and Constants

When a field is declared to be static it becomes a member of the class, where it was created (it is not associated with any object of that class). Static members are independent of any particular object derived from the class. To declare a property static, the keyword static is used
public static $number
To access a static property the class name is written followed by two colons(::) followed by the property name preceded by the $ symbol
MyClass::$number
Constants are fixed values that do not change throughout the running of a script (once it has has been initialized, it’s value can’t be changed). To declare a class variable as a constant, the const keyword is used
const VALUE=5;
It is good practice to use all-uppercase letters for a constant name. We access a constant value same way we do for a static property
MyClass::VALUE

1.5 Methods

Method are functions described in a class. To add a method to a class use the public, private or protected keyword, then the function keyword, followed by the method name, followed by parantheses. You then include the method code within curly braces. The keywords protected private and public can be left out, if this is done, PHP uses keyword public as the default.

To call an object method, simply write the object name, then the same arrow used for accessing properties(->) then the method name followed by paranthesis

$worker->getSalary();

We can also add or pass parameters to a method, so it can accept arguments to manipulate.

employee4.php

<!DOCTYPE html> 
<html lang=en>
	<head>
	<style>
	html, body{
	width:100%;
	height:100%;
	margin:0%;
	font-family:"helvetica","verdana","calibri", "san serif";
	overflow:hidden;
	padding:0%;
	border:0%;
	}
	 
	</style>
	 		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/>
	
	<title>Employee Class</title>
	
	</head>
	<body>
<?php

class employee{
public $firstname="John";
public $hasbeenpaid=false; 
public $lastname="White";
private $salary=1000;
// this method can be accessed outside the class
public function getSalary(){
return $this->salary;

}
//this functuon can only be accessed within the class
private function doSomeThing(){

}

protected function doSomeThings(){
// can be accessed within the class and any class that extend this class

}
public function increaseSalary($amount){

$this->salary=$this->salary . $amount;
echo "Salary has been increased";

}
}

$worker=new employee();
$worker->increaseSalary(1000);

?>
</body>
</html>

Edit the code above by trying to call methods that are private or protected and see how PHP responds. To access an object property from a method $this keyword is used(Line 32 and 46).

1.6 Constructors

When creating a new object it might be useful to set up certain aspects of the object at the same time. For example when creating an employee object, we might pass the employee name and position occupied, so the object can be fully initialized.

To create a constructor in PHP, simply add a method with the spcial name _construct() to your class(two underscores followed by the word construct). PHP looks for this special method name when the object is created; if it finds it, it calls the method. You can pass parameters to constructors, just like normal methods, this is great for setting certain properties to initial values as the object is created.

employee5.php

<!DOCTYPE html> 
<html lang=en>
	<head>
	<style>
	html, body{
	width:100%;
	height:100%;
	margin:0%;
	font-family:"helvetica","verdana","calibri", "san serif";
	overflow:hidden;
	padding:0%;
	border:0%;
	}
	 
	</style>
	 		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/>
	
	<title>Employee Class</title>
	
	</head>
	<body>
<?php

class employee{
public $firstname;
public $hasbeenpaid=false; 
public $lastname;
private $salary=1000;

public function __construct($first,$last){
$this->firstname=$first;
$this->lastname=$last;
}
// this method can be accessed outside the class
public function getSalary(){
return $this->salary;

}
//this functuon can only be accessed within the class
private function doSomeThing(){

}

protected function doSomeThings(){
// can be accessed within the class and any class that extend this class

}
public function increaseSalary($amount){

$this->salary=$this->salary . $amount;
echo "Salary has been increased";

}
function printUserDetails(){
echo " FirstName Is $this->firstname <br>";
echo "LastName Is $this->lastname <br>";

}
}

$worker=new employee("Jack","Daniels");
$worker->printUserDetails();

?>
</body>
</html>

On line 62 we initialize the object by passing arguments firstname and lastname to the class constructor.

2. Summary

In this example we have learnt about classes, methods,static properties, class constants and constructors, how to create and manipulate them.

3. Download the source code

Download
You can download the full source code of this example here: Phpclassexample

Olayemi Odunayo

I am a programmer and web developer, who has experience in developing websites and writing desktop and mobile applications. I have worked with both schematic and schemaless databases. I am also familiar with third party API and working with cloud servers. I do programming on the client side with Java, JavaScript, html, Ajax and CSS while I use PHP for server side programming.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button