Hello Readers,
We can use the self in static function while this is not.
we can use accessible class variable and methods with self and this are:
for self self::
for this $this->
$this needs an instantiated object while self not.
self refers to the class in which it is called, while $this refers to the class of the current object.
self can also turn off polymorphic behavior by bypassing the vtable while $this not
Examples of self anf this :
Example of self in PHP:
<?php
class Car
{
public static function model()
{
self::getModel();
}
protected static function getModel()
{
echo "I am a Car";
}
}
?>
In the above example we use a class Car and make call to the static function in the Car class.
we use the self::getModel() like
Car::model();
So the output of the above program will be:
I am a Car
Another Example of self and this in PHP:
<?php
class ParentClass {
function test() {
self::who(); // will output 'parent'
$this->who(); // will output 'child'
}
function who() {
echo 'parent';
}
}
class ChildClass extends ParentClass {
function who() {
echo 'child';
}
}
$obj = new ChildClass();
$obj->test();
?>
In this example, we use the both self ad this we use self as a (self::who()) will always output (parent)
while $this used as a ($this->who()) will depend on what class the object has.
0 Comment(s)