PHP | Common terminology in OOP
Object Oriented Programming is a very important concept for programmers to solve real life problems. This article explaining the concept of object oriented programming and it’s features.
- Object: Everything in this world is surrounded with objects. Table, chair, monitor, cellphone everything is an object. There are two things in object to remember to solve the real life problems. One is attribute and the other one is behavior. If we talk about monitor so…model number, screen size all these are attributes. On the other hand the features like volume up or volume down is behavior for monitor. In programming variables are attributes and functions are behavior.
Example:
<?php// Class definitionclassTV {// Member variablespublic$model='xyz';public$volume= 1;// Member FunctionsfunctionvolumeUp() {$this->volume++;}functionvolumeDown() {$this->volume--;}}// Create new object$tv_one=newTV;// Calling member function$tv_one->volumeUp();echo$tv_one->volume;?>chevron_rightfilter_noneOutput:2
In the above example, creating an object $tv_one of TV class and implementation of function showing the behavior of object. Initially $tv_one->volume was 1. After calling it’s function volume has been increased and displaying the updated result. $this refer to the particular or current object. You can create multiple object and show it’s behavior. Implementing this code will have the benefit of code re-usability and code will be easy to manage in future.
- Constructor function: Constructor function is an special function for which do not need to call the function like earlier we were doing after creating an object.
Example:
<?php// Class definitionclassTV {// Member variablespublic$model;public$volume;// Member FunctionsfunctionvolumeUp() {$this->volume++;}functionvolumeDown() {$this->volume--;}function__construct($m,$v) {$this->model =$m;$this->volume=$v;}}// Create new object$tv=newTV('xyz', 2);echo$tv->model;?>chevron_rightfilter_noneOutput:xyz
In the above example, assigned the value of model and volume when we are creating the object. This is the benefit of using constructor function. You don’t need to change the model number for each and every project you will be making. All need to do is to include this file and when need to create an object of TV and assign it’s value you can do that instantly while creating it’s object.
- Inheritance: In a simple word, inheritance means inheriting the properties or functionalities from one class to another class. Model and volume will find in all kind of television but suppose you need to add additional feature timer. Timer can not be included in all the television. So it will use inheritance for those television which includes timer property. Use ‘extends’ keyword to implement inheritance.
Example:
<?php// Class definitionclassTV {// Member variablespublic$model;public$volume;// Member FunctionsfunctionvolumeUp() {$this->volume++;}functionvolumeDown() {$this->volume--;}function__construct($m,$v) {$this->model =$m;$this->volume=$v;}}classTvWithTimerextendsTV {public$timer= true;}// Create new object$tv=newTvWithTimer('xyz', 2);echo$tv->model;?>chevron_rightfilter_noneOutput:xyz
Here, TVWithTimer class is a child class for TV class, whereas TV class is a parent class. The TVWithTimer class inherited all the variables and functions from it’s parent class so all the variables and functions which is in TV class will be available in TvWithTimer. So create multiple classes and inherit the property from TV class. Another important thing is Method Overriding. If defining the constructor function in child class after inheriting all the properties from parent class then the priorities will be given to child class constructor instead of parent class.
classplazmaTvextendsTV {function__construct {}}$plazma=newplazmaTv;echo$plazma->model;chevron_rightfilter_noneHere, no output will display and screen will be blank because the child class constructor is being called and it has overridden the parent class constructor. Same logic also apply for variables and you can override the variables in child class as well.
- Encapsulation: Encapsulation is all about wrapping the data and method in a single unit. In Object Oriented programming set the access level for member functions or variables. It means from where it needs to be accessed. There are three kind of access levels or access specifiers.
- Public: Public functions or variables can only be accessed from anywhere. In all the above examples, we are able to access the public functions and variables outside the class and everyone can call it.
- Private: Private functions or variables can only be accessed by the class who created it.
Example:
<?php// Class definitionclassTV {// Member variablesprivate$model;public$volume;// Member FunctionsfunctionvolumeUp() {$this->volume++;}functionvolumeDown() {$this->volume--;}function__construct($m,$v) {$this->model =$m;$this->volume=$v;}}// Create new object$tv=newTV('xyz', 2);echo$tv->model;?>chevron_rightfilter_noneOutput:
Cannot access private property TV::$model in /home/65af96133e297a6da6c1ad3d75c9ff46.php:28
The error will display after executing the above code. It means the function or variable not accessible outside the class.
- Protected: Protected functions or variables can only be used by the class who created and it’s child class means all the classes which inherit the property of parent class having protected method or variable.
Example:
<?php// Class definitionclassTV {// Member variablesprotected$model;public$volume;// Member FunctionsfunctionvolumeUp() {$this->volume++;}functionvolumeDown() {$this->volume--;}functiongetModel() {return$this->model;}function__construct($m,$v) {$this->model =$m;$this->volume=$v;}}classplazmaextendsTV {functiongetModel() {return$this->model;}}// Create new object$tv=newplazma('xyz', 1);echo$tv->getModel();?>chevron_rightfilter_noneOutput:xyz
- Abstract Classes: Like the keyword is saying, Abstract means not completed. Abstract classes are those classes where functions are declared but not implemented.
Example:
<?php// Abstruct classabstractclassABC {publicabstractfunctionxyz();}classdefextendsABC {publicfunctionxyz() {echo"Welcome to GeeksforGeeks";}}// Create new object$obj=newdef;echo$obj->xyz();?>chevron_rightfilter_noneOutput:Welcome to GeeksforGeeks
Here, created an abstract class which has one abstract method but we haven’t implemented the method in ABC base class. All the classes which will extends ABC class will have the implementation for function xyz. Here you can not make the object for ABC class. ABC class works as a base class for all it’s child classes and the implementation or object creation will be done for child classes. Declaring a class abstract class is an enforcement that you don’t want to create direct object for that class.
Example:
<?phpabstractclassBaseEmployee {protected$firstname;protected$lastname;publicfunctiongetFullName() {return$this->firstname." ".$this->lastname;}publicabstractfunctiongetMonthlySalary();publicfunction__construct($f,$l) {$this->firstname =$f;$this->lastname =$l;}}classFullTimeEmployeeextendsBaseEmployee {protected$annualSalary;publicfunctiongetMonthlySalary() {return$this->annualSalary / 12;}}classContractEmployeeextendsBaseEmployee {protected$hourlyRate;protected$totalHours;publicfunctiongetMonthlySalary() {return$this->hourlyRate *$this->totalHours;}}$fulltime=newFullTimeEmployee('fulltime','Employee');$contract=newContractEmployee('Contract','Employee');echo$fulltime->getFullName();echo$contract->getFullName();echo$fulltime->getMonthlySalary();echo$contract->getMonthlySalary();?>chevron_rightfilter_noneOutput:fulltime EmployeeContract Employee00
- Interfaces: There is a limitation for inheritance in PHP that is you can not extend multiple classes. Through Interface you can achieve multiple inheritance property. Interfaces also worked like abstract classes. The ‘implements’ keyword is used for interfaces. There is a difference between abstract class and interface class. In abstract class define variables but in interface class can not define variables. It can also not create constructor function in interfaces. It can not declare private or protected function.
Example:
<?phpinterfacea {publicfunctionabc();}interfaceb {publicfunctionxyz();}classcimplementsa, b {publicfunctionabc() {echo'GeeksforGeeks ';}publicfunctionxyz() {echo'A computer science portal';}}// Create an object$obj=newc;$obj->abc();$obj->xyz();?>chevron_rightfilter_noneOutput:GeeksforGeeks A computer science portal
- Static Members: Static variables or static functions are directly related with class. It can access static variables or functions directly with class name. Use ‘static’ keyword to declare static function or static variable.
Example:
<?php// Class definitionclassabc {publicstatic$data='GeeksforGeeks ';publicstaticfunctionxyz() {echo"A computer science portal";}}echoabc::$data;abc::xyz();?>chevron_rightfilter_noneOutput:GeeksforGeeks A computer science portal
Example: This example count how many objects we have created for a class.
<?phpclassabc {publicstatic$objectCount= 0;publicstaticfunctiongetCount() {returnself::$objectCount;}publicfunction__construct() {self::$objectCount++;}}$a=newabc();$b=newabc();$c=newabc();$d=newabc();echoabc::getCount();?>chevron_rightfilter_noneOutput:4
Note: If created object instead of static using static function or variable every time the output will be 1. So static variable or keyword is related with class not object.
- Late Static Binding: In PHP 5.3 a concept of late static binding was introduced.
Example:
<?phpclassDB {protectedstatic$table=' basetable';publicfunctionselect() {echo'SELECT * FROM'.self::$table;}publicfunctioninsert() {echo'INSERT INTO'.self::$table;}}classabcextendsDB {protectedstatic$table='abc';}$abc=newabc;$abc->select();?>chevron_rightfilter_noneOutput:SELECT * FROM basetable
Here, class DB extends class abc, but when run this code during compilation time it’s taking the table name from abc class not DB. During the compilation time PHP interpreter immediately assign the value from parent class. In order to get the variable from child class interpreter need to assign the value during runtime instead of compilation time which is happening in the above example.
echo 'SELECT * FROM' .self::$table;
or
echo 'INSERT INTO' .self::$table;
Here when interpreter will get the request it won’t assign the value during compilation time. It will be in pending for runtime. It will assign the value during runtime time and the output will be SELECT * FROM abc
- Polymorphism: Polymorphism means many types or many forms. It means suppose you have created an interface also classes which will implement this interface class. These classes will have different functionality and they all will share this common interface.
Create an interface with LoggerInterface name in LoggerInterface.php file.
<?phpinterfaceLoggerInterface {publicfunctionlog($message);}?>chevron_rightfilter_noneNow creating a file EmailLogger.php which will implement this interface.
<?phpclassEmailLoggerimplementsLoggerInterface {publicfunctionlog($message) {echo"Logging message to email: $message";}}?>chevron_rightfilter_noneCreate another file FileLogger.php and implement the interface class.
<?phpclassFileLoggerimplementsLoggerInterface {publicfunctionlog($message) {echo"Logging message to file: $message";}}?>chevron_rightfilter_noneAnother file is DBLogger.php
<?phpclassDBLoggerimplementsLoggerInterface {publicfunctionlog($message) {echo"logging message to DB: $message";}}?>chevron_rightfilter_noneNow, create an UserProfile.php file where call all these file by only defining interface name using type hinting. Do not need to define the class name for calling each and every class created in a file.
<?phpclassUserProfile {private$logger;publicfunctioncreateUser() {echo"creating user";$this->logger->log("User Created");}publicfunctionupdateUser() {echo"updating user";$this->logger->log("User Updated");}publicfunctiondeleteUser() {echo"deleting user";$this->logger->log("Deleting User");}publicfunction__construct(LoggerInterface$logger){$this->logger =$logger;}}?>chevron_rightfilter_noneNow, create a file index.php
<?phpfunction__autoload($class) {// classes is a directory where all// the above files are placed.include_once"classes/$class.php";}functiongetLogger($type) {switch($type) {case'email':returnnewEmailLogger();break;case'database':returnnewDBLogger();break;case'file':returnnewFileLogger();break;}}$logger= getLogger('database');$profile=newUserProfile($logger);$profile->createUser();?>chevron_rightfilter_noneOutput:
Creating User. Logging message to DB: User Created
So, from this example create multiple files and define their functionality. All need to implement the interface class and just give the interface name in type hinting name like I have defined in UserProfile.php file.
- Traits: Traits was introduced in PHP5.4. It is the mechanism for code reuse in single inheritance language. The ‘trait’ keyword is used to define it.
Example:
<?phpclassabc {publicfunctiontest() {echo"test from class ABC";}}traittest {publicfunctiontest2() {echo"test2 method of test trait";}}classoneextendsabc {usetest;}classtwoextendsabc {usetest;}classthreeextendsabc {}classfourextendsabc {}classfiveextendsabc {}$obj=newone;$obj->test2();?>chevron_rightfilter_noneOutput:test2 method of test trait
Here, taking a class abc and its functionality in all the child classes. So accessing the properties of abc class in all the child classes. Now consider a scenario where we need another function to be accessed only in class one and two but not in the rest of the classes. If you will define that function in the same class abc it will be available in all the classes which are extending class abc. So the solution is we can define that method in trait.
Trait is also similar to the classes. Here, define test2 function in trait test and use this trait by using ‘use’ keyword in child class. So we have used this trait only in class one and two because we need to access this method in class one and two. - Method Overriding in Traits: If defining the same method implemented in class and in trait also then preference will be given to the trait class method implementation. It means trait class method will override parent class method.
Example:
<?phpclassBase {publicfunctionabc() {echo"ABC method from base class";}}Trait Test {publicfunctionabc() {echo"ABC method from test trait";}}classchildextendsBase {useTest;}$obj=newChild;$obj->abc();?>chevron_rightfilter_noneOutput:
ABC method from test trait
So, the order of preference is child class method > trait class method > parent class method.
- Access level in traits: You can change the access level of traits in child class.
Example:
<?phptraitabc {publicfunctionxyz() {echo"xyz method from trait abc";}}classtest {useabc {abc::xyzaspublicabcXyz;}}$obj=newtest;$obj->abcXyz();?>chevron_rightfilter_noneOutput:xyz method from trait abc
- Namespaces: In PHP, class can not be redeclare. It means a class can not be declare more than once. It will display an error message. To solve this problem the concept of namespace is used.
Example:
<?phpnamespacedef {classxyz {publicfunction__construct() {echo"XYZ from DEF namespace";}}}namespace{classxyz {publicfunction__construct() {echo"XYZ from Global namespace";}}$obj=newdef/xyz();}?>chevron_rightfilter_noneOutput:
XYZ from DEF namespace
By default all the classes are part of global namespace. The global namespace declared with only keyword ‘namespace’ (no need to define the name of the namespace). The code can not be declared outside the namespace. Also namespace should be the first line in your code if you are declaring a class in it.
There is alternate way as well to call the function from def class. just replace the code like below when you create an object.use def\xyz as def; $obj = new def();
The output will be same. You can also make sub namespace for a namespace. All you just need to do when you declare it is below line.
namespace def\ghi
- Type Hinting: In PHP, don’t need to define the data type of variable you are declaring. It automatically define the data type when creating a variable, but sometimes when you receive a variable, there you need to define what kind of variable you are receiving.
Example:
<?php// Function definitionfunctiontest(array$arr) {foreach($arras$k=>$v) {echo$k." ".$v."\n";}}// Declare an array$array= ['abc'=>'ABC','xyz'=>'XYZ'];// Function calltest($array);?>chevron_rightfilter_noneOutput:abc ABC
xyz XYZSo, when receiving the variable and defined that it should be array type. If you will parse string type data $array ='abcdefgh' then you will get fatal error and the code won't execute. You can also do type hinting for class name and interface.
Recommended Posts:
- How to find if two arrays contain any common item in Javascript?
- Centralized vs Distributed Version Control: Which One Should We Choose?
- How to call PHP function on the click of a Button ?
- Difference between Organic Search and Paid Search
- How to override a JavaScript function ?
- How to get a key in a JavaScript object by its value ?
- Routing Path for ExpressJS
- How to pass variables and data from PHP to JavaScript ?
- How to get the day and month of a year using JavaScript ?
- p5.js | noLoop() Function
- p5.js | parent() Function
- HTML | input maxlength Attribute
- HTML | DOM Output value Property
- HTML | <source> Tag
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



