Home >Backend Development >PHP Tutorial >PHP object-oriented static methods, properties and constants
This article mainly introduces the static methods, properties and constants about PHP object-oriented, which has a certain reference value. Now I share it with you. Friends in need can refer to it
Static methods , attribute
Use the static
keyword definition;
Declare the class attribute or method as static, that is, you cannot Instantiate, access directly.
1) Static properties cannot be accessed through instantiated objects;
2) Static methods can be accessed;
3) Static methods , cannot use $this
:: 或 self::
The details are as follows:
访问位置 调用属性 调用方法 类的内部/外部 类名::属性名 类名::方法名 内部 self::属性名 self/类名::方法名
<?php class MyClass { // 静态属性 public static $a = 'static'; // 静态方法 public static function func1() { echo '静态方法'; // 类的内部调用静态属性 echo MyClass::$a; echo self::$a; // 类的内部调用静态方法 MyClass::func2(); self::func2(); } // 试验静态方法调用另一个静态方法 public static function func2() { echo 'This is static function 2.'; } } // 类的外部调用静态属性、方法 echo MyClass::$a; MyClass::func1(); // 实例化后再调用 $me = new MyClass(); echo $me::$a; // 调用成功 // echo $me ->a; 调用失败 $me -> func1(); // 调用成功
Constant
const
You can define values that remain unchanged in a class as constants.
The value of a constant must be a fixed value.
Call method, same as static.
class MyClass { public static $a = 'abc'; const NUM = 123; } echo MyClass::$a; echo '<br/>'; echo MyClass::NUM; echo '<br/>'; // 修改静态属性 MyClass::$a = 'def'; echo MyClass::$a; echo '<br/>'; // 修改常量 //MyClass::NUM = 234; 赋值失败
Related recommendations:
php object-oriented constructor and destructor
php object-oriented encapsulation
php object-oriented classes and instantiated objects
The above is the detailed content of PHP object-oriented static methods, properties and constants. For more information, please follow other related articles on the PHP Chinese website!