tem*_*ode 6 php static-variables
我是PHP新手并使用静态变量练习.我决定抓住一个我从C++学到的例子并重新编写它用于PHP(例如本文的底部).
有一个类有两个私有变量(一个静态),一个构造函数和一个get-method.构造函数将静态变量的值分配给第二个私有变量,然后递增.
<?php
class Something
{
private static $s_nIDGenerator = 1;
private $m_nID;
public function Something() {
$m_nID = self::$s_nIDGenerator++;
echo "m_nID: " . $m_nID . "</br>"; //for testing, can comment this out
}
public function GetID() {
return $m_nID;
}
}
// extra question:
// static variable can be assigned a value outside the class in C++, why not in PHP?
// Something::$s_nIDGenerator = 1;
$cFirst = new Something();
$cSecond = new Something();
$cThird = new Something();
echo $cFirst->GetID() . "</br>";
echo $cSecond->GetID() . "</br>";
echo $cThird->GetID() . "</br>";
?>
Run Code Online (Sandbox Code Playgroud)
使用第9行中的echo测试来查看m_nID是否得到一个值,我看到:
m_nID: 1
m_nID: 2
m_nID: 3
Run Code Online (Sandbox Code Playgroud)
但是这些值不是由" - > GetID()"调用返回的.有什么想法吗?
编辑:到目前为止这两个回复都解决了这个问题,我希望我能"检查"他们两个,谢谢!对于任何遇到类似问题的人来说,我会将原始代码保留原样
您在C++中的背景导致了这个问题,这是一个容易犯的错误.在PHP中,所有实例(或对象)变量都使用$this->和静态(或类)变量引用self::.根据您的代码:
public function GetID() {
return $m_nID;
}
Run Code Online (Sandbox Code Playgroud)
对私有变量的访问$m_nID应该是这样的:
public function GetID() {
return $this->m_nID;
}
Run Code Online (Sandbox Code Playgroud)
在你的构造函数中:
$m_nID = self::$s_nIDGenerator++;
Run Code Online (Sandbox Code Playgroud)
应该是:
$this->m_nID = self::$s_nIDGenerator++;
Run Code Online (Sandbox Code Playgroud)
问答
为什么没有必要把
$之前m_nID使用时$this->
以上两种引用实例和类变量的方法都有一种非常不同的语法:
$this是实例引用变量,使用->运算符访问任何属性; 在$不重复的属性名称本身,虽然他们目前在声明(例如private $myprop).
self::是Something::(类名本身)的同义词; 它没有引用实例变量,因此没有$它.为了区分静态变量与类常量(self::MYCONST)和类方法(self::myMethod()),它的前缀为$.
额外
也就是说,$this->$myvar也被接受并且这样工作:
private $foo = 'hello world';
function test()
{
$myvar = 'foo';
echo $this->$foo; // echoes 'hello world'
}
Run Code Online (Sandbox Code Playgroud)