pMa*_*Man 6 php inheritance constants static-variables
在PHP中,有什么区别:
我知道如何使用它们,但我无法清楚地区分它们.
Ntw*_*ike 23
可以有一个访问修饰符.
class A{
public static $public_static = "can access from anywhere";
protected static $protected_static = "can access from inheriting classes";
private static $private_static = "can access only inside the class";
}
Run Code Online (Sandbox Code Playgroud)根据可见性,您可以访问静态变量.
//inside the class
self::$variable_name;
static::$variable_name;
//outside the class
class_name::$variable_name;
Run Code Online (Sandbox Code Playgroud)声明后可以更改值.
self::$variable_name = "New Value";
static::$variable_name = "New Value";
Run Code Online (Sandbox Code Playgroud)声明时无需初始化.
public static $variable_name;
Run Code Online (Sandbox Code Playgroud)应用正常变量声明规则(例如:以$开头)
可以在函数内部创建.
class A{
function my_function(){
static $val = 12;
echo ++$val; //13
}
}
Run Code Online (Sandbox Code Playgroud)始终公开不能放置访问修饰符.
class A{
const my_constant = "constant value";
public const wrong_constant="wrong" // produce a parse error
}
Run Code Online (Sandbox Code Playgroud)您可以访问的任何地方.
//inside the class
self::variable_name;
static::variable_name;
//outside the class
class_name::variable_name;
Run Code Online (Sandbox Code Playgroud)声明后无法更改值.
self::variable_name = "cannot change"; //produce a parse error
Run Code Online (Sandbox Code Playgroud)声明时必须初始化.
class A{
const my_constant = "constant value";// Fine
const wrong_constant;// produce a parse error
}
Run Code Online (Sandbox Code Playgroud)不得在变量的开头使用$(应用其他变量规则).
class A{
const my_constant = "constant value";// Fine
const $wrong_constant="wrong";// produce a parse error
}
Run Code Online (Sandbox Code Playgroud)无法在函数内声明.
class A{
public static $public_static = "can access from anywhere";
protected static $protected_static = "can access from inheriting classes";
private static $private_static = "can access only inside the class";
const my_constant = "Constant value";
}
class B extends A{
function output(){
// you can use self or static
echo self::$public_static; //can access from anywhere;
echo self::$protected_static; //can access from inheriting classes;
self::$protected_static = "Changed value from Class B";
echo self::$protected_static; //"Changed value from Class B";
echo self::$private_static; //Produce Fatal Error
echo self::my_constant;//Constant value
}
}
Run Code Online (Sandbox Code Playgroud)