PHP static


static

Declare a class member or method to be static so that it can be accessed directly without instantiating the class, and can not access static members(except for static methods) through an object. Static members belong to the class, do not belong to any object instance, but the class object instance can be shared.

example:

class Person {
    // Define static member properties
    public static $country = "England";
    // Define static member methods
    public static function myCountry() {
        // Internal access to static member properties
        echo "I ".self::$country. "Person <br />";
    }
}
class Student extends Person {
    function study() {
        echo "I am "parent::$country. "person <br />";
    }
}
// Output member property values
echo Person::$country. "<br />"; // Output: England
$p1 = new Person();
// echo $p1->country; // Wrong Wording
// Access static member methods
Person::myCountry(); // Output: I am British
// Static methods can also be accessed through the object:
$p1->myCountry();

// Output the member attribute value in the subclass
echo Student::$country. "<br />"; // Output: England
$t1 = new Student();
$t1->study(); // Output: I am British

Run the example and output:

England
I am British
I am British
England
I am British

Summary

To access static member properties or methods inside a class, use self:(note that not $slef), such as:

Slef::$country
Slef::myCountry()

In the subclass to access the parent class static member property or method, use parent:(note that not $parent), such as:

Parent::$country
Parent::myCountry()

External Access Static member properties and methods are class name /subclass name ::, such as:

Person::$country
Person::myCountry()
Student::$country

But the static method can also be accessed through the ordinary object.




Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook