我最近一直在加强我的PHP游戏.来自JavaScript,我发现对象模型有点简单易懂.
我遇到了一些我想要澄清的怪癖,我似乎无法在文档中找到.
在PHP中定义类时,您可以定义如下属性:
class myClass {
public $myProp = "myProp";
static $anotherProp = "anotherProp";
}
Run Code Online (Sandbox Code Playgroud)
使用公共变量,$myProp我们可以使用(假设myClass在被调用的变量中引用$myClass)$myClass->myProp而不使用美元符号来访问它.
我们只能使用访问静态变量::.因此,我们可以像$myClass::$anotherProp使用美元符号一样访问静态变量.
问题是,为什么我们必须使用美元符号::而不是->?
编辑
这是我认为可以工作的代码(并且确实):
class SethensClass {
static public $SethensProp = "This is my prop!";
}
$myClass = new SethensClass;
echo $myClass::$SethensProp;
Run Code Online (Sandbox Code Playgroud)
Mic*_*ski 16
一类常量与访问::范围运营,并没有美元符号,所以$需要有静态类属性和类常量来区分.
class myClass {
public static $staticProp = "static property";
const CLASS_CONSTANT = 'a constant';
}
echo myClass::CLASS_CONSTANT;
echo myClass::$staticProp;
Run Code Online (Sandbox Code Playgroud)
因此,要访问变量,这$是必要的.但是$不能将它放在类名的开头,$myClass::staticProp因为然后解析器无法识别类名,因为它也可以使用变量作为类名.因此必须附在酒店.
$myClass = "SomeClassName";
// This attempts to access a constant called staticProp
// in a class called "SomeClassName"
echo $myClass::staticProp;
// Really, we need
echo myClass::$staticProp;
Run Code Online (Sandbox Code Playgroud)