pTutorial

New way to learn PHP

PHP 5 self and parent keyword

self and parent keyword

PHP provides two keywords that work with the scope resolution operator are following below.

Self keyword: This refers to the current class and it is usually used to access static methods, property and constant.

Parent keyword: This refers to the parent class. It is used often to when we want to call the parent constructor or method.

Example

<?php

Class Car
{
Const NAME = " Audi";
}

class Model extends Car
{
Const MOD = " R 8 ";

Const COLOR= " Black ";

public static function get()
{
echo "
Name of Brand:".parent::NAME; echo "
Model of Car:".self::MOD; echo "
Color of Car:".self::COLOR; } } echo "Name of Brand:"; echo Car::NAME; Model::get(); ?>

Output

Name of Brand: Audi
Name of Brand: Audi
Model of Car: R 8
Color of Car: Black

In the above example, there are two classes Car and Model and Model is the child of Car class. Both have some property and behavior. If you want to access the static property or behavior of the parent class, then use parent keyword and if you want to access the static property or behavior of the child class then use self keyword, as shown above

Static property with object

<?php

Class Car
{
Const NAME = " Audi";
}
 

 
class model extends Car
{
Const MOD = " R 8 ";
 
Const COLOR= " Black ";
 
public function get()
{
echo "
Name of Brand:".parent::NAME; echo "
Model of Car:".self::MOD; echo "
Color of Car:".self::COLOR; } } $uk=new model(); $uk->get(); ?>

Output

Name of Brand: Audi
Model of Car: R 8
Color of Car: Black

Download Source code


QUOTES OF THE DAY

Impossible is a word only be found in the dictionary of fools.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER