PHP tutorial: OOP


Object-oriented programming is a method that allows programmers to use classes and objects to store and structure their programs. In PHP and other object-oriented programming languages such as C++, Java, C#, Small talk, or Ruby, classes, objects, and their relationships are the core of object-oriented programming. Class is a template that can be used to create an object. Therefore, object is the instance of the class.

Creating a class and object

      To create a class, you must use class keyword followed by the name of the class. The objects of the class can be created by using new keyword.
Example: create a class named Employee
class Employee



A class can have members. The members can be data members and method members. Data members can be private, protected, and public. A private member can only accessed in the class that defines it. A protected member is accessible in the class and its derived class. A public member can be accessed in code outside the class that defines it.

To define a method member, you need to use function keyword.


class Employee
//data members
private $emp_id;
private $emp_name;
private $emp_sex;
private $emp_salary;
//method members
function setName(){
$this->emp_name="Dara Yuk";
function getName(){
return $this->emp_name;


$emp=new Employee();//create object
$emp->setName();//accessing setName method member
echo $emp->getName();//accessing getName method member


This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.