如何设置公共变量。它是否正确?:
class Testclass
{
public $testvar = "default value";
function dosomething()
{
echo $this->testvar;
}
}
$Testclass = new Testclass();
$Testclass->testvar = "another value";
$Testclass->dosomething();
这是方法,但我建议为该变量编写一个 getter 和 setter。
class Testclass
{
private $testvar = "default value";
public function setTestvar($testvar) {
$this->testvar = $testvar;
}
public function getTestvar() {
return $this->testvar;
}
function dosomething()
{
echo $this->getTestvar();
}
}
$Testclass = new Testclass();
$Testclass->setTestvar("another value");
$Testclass->dosomething();
使用构造函数。
<?php
class TestClass
{
public $testVar = "default value";
public function __construct($varValue)
{
$this->testVar = $varValue;
}
}
$object = new TestClass('another value');
print $object->testVar;
?>
class Testclass
{
public $testvar;
function dosomething()
{
echo $this->testvar;
}
}
$Testclass = new Testclass();
$Testclass->testvar = "another value";
$Testclass->dosomething(); ////It will print "another value"
内部class Testclass
:
public function __construct($new_value)
{
$this->testvar = $new_value;
}
您正在“设置”该变量/属性的值。不覆盖或重载它。你的代码非常非常普通和正常。
所有这些术语(“set”、“override”、“overload”)都有特定的含义。覆盖和重载是关于多态性(子类化)。
来自http://en.wikipedia.org/wiki/Object-oriented_programming:
多态性允许程序员像对待父类的成员一样对待派生类成员。更准确地说,面向对象编程中的多态性是属于不同数据类型的对象响应同名方法的方法调用的能力,每个方法调用都根据适当的特定于类型的行为。一种方法或运算符(例如 +、- 或 *)可以抽象地应用于许多不同的情况。如果命令 Dog 说话(),这可能会引发吠声()。但是,如果命令 Pig 说话(),这可能会引发 oink()。它们都继承自 Animal 的 speak(),但它们的派生类方法覆盖了父类的方法;这是覆盖多态性。重载多态是使用一种方法签名,或一种运算符,例如“+”,根据实现执行几个不同的功能。例如,“+”运算符可用于执行整数加法、浮点加法、列表连接或字符串连接。Number 的任何两个子类,例如 Integer 和 Double,都应该在 OOP 语言中正确地相加。因此,该语言必须重载加法运算符“+”才能以这种方式工作。这有助于提高代码的可读性。这是如何实现的因语言而异,但大多数 OOP 语言至少支持某种程度的重载多态性。预计将在 OOP 语言中正确添加。因此,该语言必须重载加法运算符“+”才能以这种方式工作。这有助于提高代码的可读性。这是如何实现的因语言而异,但大多数 OOP 语言至少支持某种程度的重载多态性。预计将在 OOP 语言中正确添加。因此,该语言必须重载加法运算符“+”才能以这种方式工作。这有助于提高代码的可读性。这是如何实现的因语言而异,但大多数 OOP 语言至少支持某种程度的重载多态性。
对于重载,您需要一个子类:
class ChildTestclass extends Testclass {
public $testvar = "newVal";
}
$obj = new ChildTestclass();
$obj->dosomething();
此代码将回显newVal
。
将 getter 和 setter 方法添加到您的类。
public function setValue($new_value)
{
$this->testvar = $new_value;
}
public function getValue()
{
return $this->testvar;
}
如果您要遵循给出的示例(使用 getter/setter 或在构造函数中设置它)将其更改为私有,因为这些是控制变量中设置的内容的方法。
将所有这些添加到类中的东西保持公开是没有意义的。