Static Keyword In PHP

Here we discuss use of static keyword in php oops. In php we can use static keyword with properties and methods. When we declared any method or properties as static then we can access methods and properties without creating object of that class.

1. With Methods

class Phpguruji {
    public static function callStaticMethod() {
        // ...
    }
}

Phpguruji::callStaticMethod();

2. With Properties

class Parent
{
    public static $static_pro = 'Parent';

    public function staticValue() {
        return self::$static_pro;
    }
}

class Child extends Parent
{
    public function ParentStatic() {
        return parent::$static_pro;
    }
}

print Parent::$static_pro . "\n";

$Parent = new Parent();
print $Parent->staticValue() . "\n";
print $Parent->static_pro . "\n";      // Undefined "Property" static_pro 

print $Parent::$static_pro . "\n";

print Child::$static_pro . "\n";
$Child = new Child();
print $Child->ParentStatic() . "\n";

Leave a Reply

Your email address will not be published. Required fields are marked *