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.
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;
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!"; } }
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(); } }
You can get the output:
Car BMW has created! Car Car name is BMW Car BMW has destory!
[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!