PHP. OOP. Static properties and methods

Home » Tutorials » PHP » PHP. OOP. Static properties and methods
PHP supports static properties and methods. For declaration of static method or property php has got static keyword
Accessing to static properties and methods doesn’t suppose object creating. While trying to access a static property through class object you will get an error. But from php 5.3 you may access to static method through class object.
Intro static method you can’t use $this. It is true, because static property “glues” to class. $this suppose dynamic accessing to property or method.
Also we considered situation with accessing to own and parent static properties. Accessing to own class property intro static method realizes with self keyword. if you need to access a static parent property, you need to use parent keyword.

Code lesson

<?php
/*
** Статические свойства и методы
**/

class Man {

    public static $name = "Камиль";
    public $surname = "Абзалов";

    public static function staticMethod()
    {
        echo "Вывод статического свойства в статическом методе " .  self::$name;
    }
}

class Kamil extends Man {

    public static $name = "Камиль Абзалов";

    public static function staticMethod() {
        echo "Вывод статического свойства в статическом метода " .  self::$name;
        echo "<br>";
        echo "Вывод родительского статического свойства в дочернем статическом методе " .  parent::$name;
    }

}

$man = new Man();
$kamil = new Kamil();

print_r($man);
echo "<br>";

print_r($kamil);
echo "<br>";

echo Man::$name;
echo "<br>";

echo Kamil::$name;
echo "<br>";

echo Man::staticMethod();
echo "<br>";

echo Kamil::staticMethod();
echo "<br>";

0 Comments

Submit a Comment

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


The reCAPTCHA verification period has expired. Please reload the page.

Pin It on Pinterest

Share This