设置公共类变量
如何设置公共变量。这是正确的吗?:
class Testclass
{
public $testvar = "default value";
function dosomething()
{
echo $this->testvar;
}
}
$Testclass = new Testclass();
$Testclass->testvar = "another value";
$Testclass->dosomething();
How do I set a public variable. Is this correct?:
class Testclass
{
public $testvar = "default value";
function dosomething()
{
echo $this->testvar;
}
}
$Testclass = new Testclass();
$Testclass->testvar = "another value";
$Testclass->dosomething();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
就是这样,但我建议为该变量编写一个 getter 和 setter。
this is the way, but i would suggest to write a getter and setter for that variable.
使用构造函数。
Use Constructors.
对于重载,您需要一个子类:
此代码将回显
newVal
。For overloading you'd need a subclass:
This code would echo
newVal
.您正在“设置”该变量/属性的值。不覆盖或超载它。你的代码非常非常常见和正常。
所有这些术语(“设置”、“覆盖”、“过载”)都有特定的含义。 Override 和 Overload 与多态性(子类化)有关。
来自 http://en.wikipedia.org/wiki/Object-oriented_programming :
You're "setting" the value of that variable/attribute. Not overriding or overloading it. Your code is very, very common and normal.
All of these terms ("set", "override", "overload") have specific meanings. Override and Overload are about polymorphism (subclassing).
From http://en.wikipedia.org/wiki/Object-oriented_programming :
如果您打算遵循给出的示例(使用 getter/setter 或在构造函数中设置它),请将其更改为 private,因为这些是控制变量中设置内容的方法。
将所有这些东西添加到类中而将属性保持为公共是没有意义的。
If you are going to follow the examples given (using getter/setter or setting it in the constructor) change it to private since those are ways to control what is set in the variable.
It doesn't make sense to keep the property public with all those things added to the class.
将 getter 和 setter 方法添加到您的类中。
Add getter and setter method to your class.
在
class Testclass
内:Inside
class Testclass
: