何时应在 PHP 类中声明变量?
我是OOP范式的新手,所以对于这个问题可能有一个简单的解释......
是否总是需要在类中声明公共对象范围的变量?例如:
<?php
class TestClass
{
var $declaredVar;
function __construct()
{
$this->declaredVar = "I am a declared variable.";
$this->undeclaredVar = "I wasn't declared, but I still work.";
}
function display()
{
echo $this->declaredVar . "<br />";
echo $this->undeclaredVar;
echo "<br /><br />";
}
}
$test = new TestClass;
$test->display();
$test->declaredVar = "The declared variable was changed.";
$test->undeclaredVar = "The undeclared variable was changed.";
$test->display();
?>
在这个代码中,即使是唯一声明的变量,也是同样可访问和可用的 - 它似乎就像我已将其声明为公共一样。$declaredVar
$undeclaredVar
如果未声明的类变量总是可以像这样访问的,那么预先声明它们有什么意义呢?