OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or functions that perform operations on the data, while object-oriented programming is about creating objects that contain both data and functions.
Object-oriented programming has several advantages over procedural programming:
a class is a template for objects
example: fruit
Define a class: <?php class Fruit{ } ?>
Below we declare a class named Fruit consisting of two properties ($name and $color) and two methods set_name() and get_name() for setting and getting the $name property:
<?php class Fruit { // Properties public $name; public $color; // Methods function set_name($name) { $this->name = $name; } function get_name() { return $this->name; } } ?>
an object is an instance of a class
example: banana,apple,mango
Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values.
Objects of a class is created using the new keyword.
In the example below, $apple and $banana are instances of the class Fruit:
<?php class Fruit { // Properties public $name; public $color; // Methods function set_name($name) { $this->name = $name; } function get_name() { return $this->name; } } $apple = new Fruit(); $banana = new Fruit(); $apple->set_name('Apple'); $banana->set_name('Banana'); echo $apple->get_name(); echo "<br>"; echo $banana->get_name(); ? >
The $this keyword refers to the current object, and is only available inside methods.
Example
<?php
class Fruit {
// Methods
function set_name($name) {
$this->name = $name;
}
}
?>
1. Inside the class (by adding a set_name() method and use $this): ?php class Fruit { public $name; function set_name($name) { $this->name = $name; } } $apple = new Fruit(); $apple->set_name("Apple"); ?> 2. Outside the class (by directly changing the property value): ?php class Fruit { public $name; } $apple = new Fruit(); $apple->name = "Apple"; ?>
You can use the instanceof keyword to check if an object belongs to a specific class:
?php $apple = new Fruit(); var_dump($apple instanceof Fruit); ?>
A constructor allows you to initialize an object's properties upon creation of the object.
If you create a __construct() function, PHP will automatically call this function when you create an object from a class.
Notice that the construct function starts with two underscores (__)!
Note:multipel contructor can not declar in php,if use parameter in contruction then when create object must user parameter otherwise error occurs,any private attibute can not instantciate by the object?php class Fruit { public $name; public $color; function __construct($name) { $this->name = $name; } function get_name() { return $this->name; } } $apple = new Fruit("Apple"); echo $apple->get_name(); ?>
A destructor is called when the object is destructed or the script is stopped or exited.
If you create a __destruct() function, PHP will automatically call this function at the end of the script.
Notice that the destruct function starts with two underscores (__)!
The example below has a __construct() function that is automatically called when you create an object from a class, and a __destruct() function that is automatically called at the end of the script:?php class Fruit { public $name; public $color; function __construct($name) { $this->name = $name; } function __destruct() { echo "The fruit is {$this->name}."; } } $apple = new Fruit("Apple"); ?>
Constants cannot be changed once it is declared. Class constants can be useful if you need to define some constant data within a class. A class constant is declared inside a class with the const keyword. Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters. We can access a constant from outside the class by using the class name followed by the scope resolution operator (::) followed by the constant name, like here:
?php class Goodbye { const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!"; } echo Goodbye::LEAVING_MESSAGE; ?>
Or, we can access a constant from inside the class by using the self keyword followed by the scope resolution operator (::) followed by the constant name, like here:
?php class Goodbye { const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!"; public function byebye() { echo self::LEAVING_MESSAGE; } } $goodbye = new Goodbye(); $goodbye->byebye(); ?>
With Type hinting we can specify the expected data type (arrays, objects, interface, etc.) for an argument in a function declaration. This practice can be most advantageous because it results in better code organization and improved error messages
Array type hintingfunction calcNumMilesOnFullTank(array $models) { foreach($models as $item) { echo $carModel = $item[0]; echo " : "; echo $numberOfMiles = $item[1] * $item[2]; echo "Object type hinting
"; } }
class Test1 { public $var= "hello javatpoint and SSSIT"; } //create function with class name argument function typehint(Test1 $t1) { //call variable echo $t1->var; } //call function with call name as a argument typehint(new Test1());hinting to basic data types
class car { protected $model; protected $hasSunRoof; protected $numberOfDoors; protected $price; // string type hinting public function setModel(string $model) { $this->model = $model; } // boolean type hinting public function setHasSunRoof(bool $value) { $this->hasSunRoof = $value; } // integer type hinting public function setNumberOfDoors(int $value) { $this->numberOfDoors = $value; } // float type hinting public function setPrice(float $value) { $this->price = $value; } }
Static methods can be called directly - without creating an instance of a class.Static methods are declared with the static keyword:
?php class greeting { public static function welcome() { echo "Hello World!"; } } // Call static method greeting::welcome(); ?>
A class can have both static and non-static methods. A static method can be accessed from a method in the same class using the self keyword and double colon (::):
?php class greeting { public static function welcome() { echo "Hello World!"; } public function __construct() { self::welcome(); } } new greeting(); ?>
Static methods can also be called from methods in other classes. To do this, the static method should be public:
?php class greeting { public static function welcome() { echo "Hello World!"; } } class SomeOtherClass { public function message() { greeting::welcome(); } } ?>
To call a static method from a child class, use the parent keyword inside the child class. Here, the static method can be public or protected.
?php class domain { protected static function getWebsiteName() { return "W3Schools.com"; } } class domainW3 extends domain { public $websiteName; public function __construct() { $this->websiteName = parent::getWebsiteName(); } } $domainW3 = new domainW3; echo $domainW3 -> websiteName; ?>
Static properties can be called directly - without creating an instance of a class.Static properties are declared with the static keyword:
?php class pi { public static $value = 3.14159; } // Get static property echo pi::$value; ?>
A class can have both static and non-static properties. A static property can be accessed from a method in the same class using the self keyword and double colon (::):
?php class pi { public static $value=3.14159; public function staticValue() { return self::$value; } } echo pi::$value."
"; // ok $pi = new pi(); echo $pi->staticValue(); // ok ?>
A class can have both static and non-static properties. A static property can be accessed from a method in the same class using the self keyword and double colon (::):
?php class pi { public static $value=3.14159; public function staticValue() { return self::$value; } } $pi = new pi(); echo $pi->staticValue(); ?>
To call a static property from a child class, use the parent keyword inside the child class:
?php class pi { public static $value=3.14159; } class x extends pi { public function xStatic() { return parent::$value; } } // Get value of static property directly via child class echo x::$value; // or get value of static property via xStatic() method $x = new x(); echo $x->xStatic();
Namespaces are qualifiers that solve two different problems:
Namespaces are declared at the beginning of a file using the namespace keyword:
namespace Html;
We may have a set of classes which describe an HTML table, such as Table, Row and Cell while also having another set of classes to describe furniture, such as Table, Chair and Bed. Namespaces can be used to organize the classes into two different groups while also preventing the two classes Table and Table from being mixed up.
<?php namespace Html; class Table { public $title = ""; public $numRows = 0; public function message() { echo "Table '{$this->title}' has {$this->numRows} rows.
"; } } $table = new Table(); $table->title = "My table"; $table->numRows = 5; $table->message(); //namespace Furniture; // if off then Cannot declare class Html\Table, because the name is already in use class Table { public $title = ""; public $num = 0; public function message() { echo "This '{$this->title}' has {$this->num} seat.
"; } } $table = new Table(); $table->title = "Sofa"; $table->num = 4; $table->message(); ?>
If we keep the above two class in the location:php/mycode/Table.php and php/mycode/MyTable.php respectively then we can access by the namespace
<?php
require 'mycode/Table.php'; // folder and file location
use Html\Table; // namespace and class name
$table = new Table();
//$table = new Html\Table();
$table->title = "My table";
$table->numRows = 5;
$table->message();
?>
<?php
require 'mycode/MyTable.php';
use Furniture\Table;
$table = new Table();
$table->title = "My table";
$table->numRows = 5;
$table->message();
?>
Namespace Alias
use Html as H; $table = new H\Table();
use Html\Table as T; $table = new T();
PHP only supports single inheritance: a child class can inherit only from one single parent. So, what if a class needs to inherit multiple behaviors? OOP traits solve this problem. Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).
Traits are declared with the trait keyword:
trait TraitName { // some code... }To use a trait in a class, use the use keyword:
class MyClass { use TraitName; }
trait message1 { public function msg1() { echo "OOP is fun! "; } } trait message2 { public function msg2() { echo "OOP reduces code duplication!"; } } class Welcome2 { use message1, message2; } $obj2 = new Welcome2(); $obj2->msg1(); $obj2->msg2();
Properties and methods and Class can have access modifiers which control where they can be accessed.
There are three access modifiers:
<?php
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private
class MyClass2 extends MyClass
{
// We can redeclare the public and protected properties, but not private
public $public = 'Public2';
protected $protected = 'Protected2';
private $private = 'Private2';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj2 = new MyClass2();
echo $obj2->public; // Works
echo $obj2->protected; // Fatal Error
echo $obj2->private; // Undefined
$obj2->printHello(); // Shows Public2, Protected2, Undefined
?>
EXAMPLE 1: Public
<?php class demo{ public $name="Ajeet"; function disp(){ echo $this->name."EXAMPLE 2: Protected
"; } } $dd = new demo(); echo $dd->name="Uzzal"; // Uzzal echo $dd->disp(); // Uzzal
<?php
class demo{
protected $name="Ajeet";
protected function disp(){
echo $this->name."";
}
}
class child extends demo{
function disp(){
echo $this->name."";
}
protected function disp2(){
echo "hii";
}
}
$dd = new child();
//echo $dd->name="Uzzal"; // Cannot access protected property
echo $dd->disp(); // ok
echo $dd->disp2(); // Uncaught Error: Call to protected method child::disp2()
EXAMPLE 3: Private
<?php class demo{ private $name="Ajeet"; private function disp(){ echo $this->name."EXAMPLE 4: Abstract
"; } function ukshow(){ return $this->disp(); } function ukshow2(){ return $this->disp(); } } $dd = new demo(); //echo $dd->name; // Cannot access private property //echo $dd->disp(); // Uncaught Error: Call to private method demo::disp() echo $dd->ukshow(); // ok echo $dd->ukshow2(); // ok
<?php abstract class demo{ public $name="Ajeet"; private function disp(){ echo $this->name."EXAMPLE 5: final
"; } } class child extends demo{ function disp(){ echo $this->name."
"; } } //$dd = new demo(); //echo $dd->disp(); // Cannot instantiate abstract class demo $dd2 = new child(); echo $dd2->disp(); // ok
<?php final class demo{ public $name="Ajeet"; public function disp(){ echo $this->name."EXAMPLE 6: static
"; } } /*class child extends demo{ function disp(){ echo $this->name."
"; } } */ // error: Class child may not inherit from final class (demo) $dd = new demo(); echo $dd->disp(); // ok
<?php class demo{ public static $name="Ajeet"; public $uktitle ="Modak"; public function disp(){ echo self::$name."
"; } public static function uk(){ return self::$name."
"; } } //Note: We can not declare a class static accept properties and method class child extends demo{ public static function uk(){ echo self::$name."
"; } } // error: Cannot make static method demo::uk() non static in class child $dd = new demo(); //$dd->name; // error property can not access with -> $dd->uktitle; // ok echo $dd->disp(); // okk echo $dd->uk(); // okk function can access with -> echo demo::disp(); // ok echo demo::$name; // ok //echo demo::$uktitle; // error echo demo::uk(); // ok $dd2 = new child(); //$dd2->name; // error echo $dd2->uk(); // okk echo child::uk() // okk // note if any property static then all thethod can be access with :: // static method can be access with -> but property not. // class can not declare static
An interface is similar to a class except that it cannot contain code. An interface can define method names and arguments, but not the contents of the methods. Any classes implementing an interface must implement all methods defined by the interface. A class can implement multiple interfaces. An interface is declared using the "interface" keyword. Interfaces can't maintain Non-abstract methods. all the abstract methods in an interface have public visibility
interface a { public function dis1(); } interface b { public function dis2(); } class demo implements a,b { public function dis1() { echo "method 1..."; } public function dis2() { echo "method2..."; } } $obj= new demo(); $obj->dis1(); $obj->dis2();
An abstract class is a class that contains at least one abstract method. An abstract method is a method that is declared, but not implemented in the code.An abstract class or method is defined with the abstract keyword:
When inheriting from an abstract class, the child class method must be defined with the same name, and the same or a less restricted access modifier. So, if the abstract method is defined as protected, the child class method must be defined as either protected or public, but not private. Also, the type and number of required arguments must be the same. However, the child classes may have optional arguments in addition.
So, when a child class is inherited from an abstract class, we have the following rules:
<?php // Parent class abstract class Car { public $name; public function __construct($name) { $this->name = $name; } abstract public function intro() : string; } // Child classes class Audi extends Car { public function intro() : string { return "Choose German quality! I'm an $this->name!"; } } class Volvo extends Car { public function intro() : string { return "Proud to be Swedish! I'm a $this->name!"; } } class Citroen extends Car { public function intro() : string { return "French extravagance! I'm a $this->name!"; } } // Create objects from the child classes $audi = new audi("Audi"); echo $audi->intro(); echo "
"; $volvo = new volvo("Volvo"); echo $volvo->intro(); echo "
"; $citroen = new citroen("Citroen"); echo $citroen->intro(); ?>
The wrapping up of data and methods into a single unit (called class) is known as encapsulation. Encapsulation is a protection mechanism for the data members and methods present inside the class. In the encapsulation technique, we are restricting the data members from access to outside world end-user.
In PHP, encapsulation utilized to make the code more secure and robust. Using encapsulation, we are hiding the real implementation of data from the user and also does not allow anyone to manipulate data members except by calling the desired operation.
When we wrap our data into something then it hides details from the user who uses it.
For example: When we create an Object from a Class we don’t know what has been written inside the constructor. How it initializes the value of the member variable, How member function we use through object manipulates the value of the member variables or how it generates the output.
This is the main reason for which we use encapsulation so that unnecessary details should be hidden from users who use the class. To achieve this we often make Member Variables private, So that it cannot be accessed outside the class and if someone wants to access these variable, it should be through the GETTER and SETTER methods.
Example of Encapsulationclass ATM { private $custid; private $atmpin; public function PinChange($custid,$atmpin) { ---------perform tasks----- } public function CheckBalance($custid,$atmpin){ ---------perform tasks----- } public function miniStatement($custid) { ---------perform tasks----- } } $obj = new ATM(); $obj ->CheckBalance(10005285637,1**3);
In this example, all the ATM class data members (variable) are marked with the private modifier. It implies that we can not directly access ATM class data members (property). So, we can't change the class property directly. The only approach to change the class property (data members) is calling a method (function). That’s the reason we have stated all the ATM class methods with a public access modifier. The user can pass the expected arguments to a class method to perform a particular task.
Suppose anyone wants to check balance then he needs to access the CheckBalance() method with the required arguments custid="10005285637"andatmpin="1**3". This is called Data hiding through Encapsulation.
This word is can from Greek word poly and morphism. Poly means "many" and morphism means property which help us to assign more than one property. => Overloading Same method name with different signature, since PHP doesn't support method overloading concept => Overriding When same methods defined in parents and child class with same signature i.e know as method overriding
<?php
class base{
function add($a,$b){
$res=$a+$b;
echo "Sum of two number = ".$res;
}
}
class child extends base{
function add($a,$b,$c){
$res=$a+$b+$c;
echo "Sum of three number = ".$res;
}
}
$obj= new child();
$obj->add(1000,500);
Output Warning: Missing argument 3 for child::add(), called in C:xampplitehtdocsdboverriding.php on line 21 and defined in C:xampplitehtdocsdboverriding.php on line 13 Sum of three number = 1500
?>
<?php
class base{
function add($a,$b){
$res=$a*$b;
echo "Multiplication = ".$res;
}
}
class child extends base{
function add($a,$b){
$res=$a+$b;
echo "Sum = ".$res;
}
}
$obj= new child();
$obj->add(1000,500);
?>
Output Sum = 1500
In the above example class base have a method add with two signature the same method name with same signature defined in class child also. But when we call the method add( ) through object of its child, its own method have performed (addition of two number). It means child class add( ) method override its base class method add( ).
interface Machine { public function calcTask(); } class Circle implements Machine { private $radius; public function __construct($radius){ $this -> radius = $radius; } public function calcTask(){ return $this -> radius * $this -> radius * pi(); } } class Rectangle implements Machine { private $width; private $height; public function __construct($width, $height){ $this -> width = $width; $this -> height = $height; } public function calcTask(){ return $this -> width * $this -> height; } } $mycirc = new Circle(3); $myrect = new Rectangle(3,4); echo $mycirc->calcTask(); echo $myrect->calcTask();
When a class derives from another class.
The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods.
PHP supports Single inheritance. Single inheritance is a concept in PHP in which one class can be inherited by a single class only. We need to have two classes in between this process. One is the base class (parent class) and the other a child class itself
<?php
class MyAccess {
var $var = "This is first var";
protected $fist_name;
// simple class method
function returnVar() {
echo $this->fist_name;
}
function set_fist_name($set_this){
$this->fist_name = $set_this;
}
}
class Child extends MyAccess {
function setVal($set_this){
$this->fist_name = $set_this;
}
function getVal(){
echo $this->fist_name;
}
}
$obj1 = new Child();
$obj1->setVal("Jai Shre");
$obj1->getVal();
?>
output:Jai Shre
PHP supports Multilevel Inheritance. In this type of inheritance, we will have more than 2 classes. In this type of inheritance, a parent class will be inherited by a child class then that child class will be inherited by the child class
<?php class ParentClass { var $var = "This is first var"; public $fist_name; // simple class method function returnVar() { echo $this->fist_name; } function set_fist_name($set_this){ $this->fist_name = $set_this; } } class child_1 extends ParentClass { function setVal($set_this){ $this->fist_name = $set_this; } function getVal(){ echo "Extended By Parent Class -". $this->fist_name; } } class child_2 extends child_1 { function setVal($set_this){ $this->fist_name = $set_this; } function getVal(){ echo "Extended By child 1 - ".$this->fist_name; } } $obj1 = new child_1(); $obj1->setVal("This is first inherited class"); $obj1->getVal(); echo "
"; $obj2 = new child_2(); $obj2->setVal("This is second inherited class"); $obj2->getVal(); ?>
PHP supports Hierarchical inheritance. Hierarchical inheritance is the type of inheritance in which a program consists of a single parent and more than one child class
<?php class ParentClass { var $var = "This is first var"; public $fist_name; // simple class method function returnVar() { echo $this->fist_name; } function set_fist_name($set_this){ $this->fist_name = $set_this; } } class child_1 extends ParentClass { function setVal($set_this){ $this->fist_name = $set_this; } function getVal(){ echo $this->fist_name; } } class child_2 extends ParentClass { function setVal($set_this){ $this->fist_name = $set_this." - ".$set_this;; } function getVal(){ echo $this->fist_name; } } $obj1 = new child_1(); $obj1->setVal("This is first child class"); $obj1->getVal(); echo "
"; $obj2 = new child_2(); $obj2->setVal("This is second child class"); $obj2->getVal(); ?>
Total : 26654
Today :3
Today Visit Country :