Home > Backend Development > PHP Problem > What does php static mean?

What does php static mean?

藏色散人
Release: 2023-03-10 13:22:01
Original
2836 people have browsed it

php static is a keyword in PHP. Using the static keyword means that the member is a static member. Only one copy will be retained during the loading process of the class. All operations on static variables will All objects work.

What does php static mean?

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

What does php static mean?

The role and difference of the static keyword in PHP

static in PHP is different from other object-oriented languages ​​such as Java. An instantiated object only Static methods can be accessed, but static members cannot be accessed.

Using the static keyword means that the member is a static member. Only one copy will be retained during the loading process of the class. All operations on static variables will affect all objects.

In Static variables in PHP cannot be called by instantiated objects, static methods can be called by objects

// ----类内部----
// 调用普通成员
this->name;
// 调用静态成员
self::name_static;
// ----类外部----
// 调用普通成员需要实例化使用
Car c = new Car();
c->name;
// 调用静态方法
c::fun()  <==>  Car::fun()
// 调用静态变量
Car::name;
Copy after login

Analyze a piece of code:

class Car
{
    private $name;
    private static $type = "Car";
    function __construct($name)
    {
        $this->name = $name;
        echo "Car " . $name . " has created!\n";
    }
    public static function getType()
    {
        echo self::$type . "\n";
    }
    public function getName()
    {
        echo "Car name is " . $this->name . "\n";
    }
    function __destruct()
    {
        echo "Car " . $this->name . " has destory!";
    }
}
Copy after login

An entity class defines a constructor, a static function, and a Ordinary function, a destructor, an ordinary member variable, and a static member variable.

Use PHPunit for testing

class  test extends PHPUnit_Framework_TestCase
{
    public function test_car()
    {
        $car = new Car("BMW");
        $car::getType();
        $car->getName();
    }
}
Copy after login

You can get the output:

Car BMW has created!
Car
Car name is BMW
Car BMW has destory!
Copy after login

[Recommended learning: PHP video tutorial]

The above is the detailed content of What does php static mean?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template