PHP OOPs
OOP (Object Oriented Programming) is a programming paradigm, which is based on the concept of the object. It contains data in several formats I.e properties, attributes & methods, Which is derived by a class object.
How to access attributes and procedures(methods)
To access attributes and procedures, It uses “this” or “self” notion.
Before PHP 5, PHP follows only procedural methods to develop applications. In earlier PHP 5, PHP started a rewritten object model to improve application performance and features. It’s a major change in PHP from PHP4 to PHP5.
PHP 5 provided several features I.e visibility, abstract and final classes, and methods, additional magic methods, interfaces, cloning, and type hinting.
Example of simple class
<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar()
{
echo $this->var;
}
}
?>
Example of simple class with $this pseudo-variable
<?php
class A
{
function foo()
{
if (isset($this))
{
echo '$this is defined (';
echo get_class($this);
echo ")\n";
}
else
{
echo "\$this is not defined.\n";
}
}
}
class B
{
function bar()
{
A::foo();
}
}
$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>
Output of the above example in PHP 5:
$this is defined (A)
$this is not defined.
$this is defined (B)
$this is not defined.
Output of the above example in PHP 7:
$this is defined (A)
$this is not defined.
$this is not defined.
$this is not defined.
Why is new keyword used
The new keyword is used to create an instance of a class, An object will always be created unless the object has a constructor defined that throws an exception on error.
When a class with new keyword assigned to a variable, a new instance of the class is created and assigned to this variable. This variable is used to access the attributes & methods of this class.
If a class has namespace then, before creating an instance of a class, It’s the full name of the class with a namespace is required.
Example
<?php
$instance = new SimpleClass();
// This can also be done with a variable:
$className = 'SimpleClass';
$instance = new $className(); // new SimpleClass()
?>
In the class context, it is possible to create a new object by new self and new parent.
Example with namespace
<?php
namespace Sample;
$instance = new \Sample\SimpleClass();
?>
How to accesses property & method of a class with instance
<?php
class Foo
{
public $bar = 'property';
public function bar() {
return 'method';
}
}
$obj = new Foo();
$obj->bar; // access of property
$obj->bar(); // access of method
?>