假设我有以下类:
class MyClass {
public function Talk() {
$Say = "Something";
return $Say;
}
}
然后我启动了一个类的实例:
$Inst = new MyClass();
我现在如何在MyClass之外调用$Say,因此,例如,在文档上回显它?例如:
$Said = "He" . $Say
我强烈建议您通读http://php.net/manual/en/language.oop5.php。它将教你在PHP中OOP的基础知识。
在您的示例中,$Say
只是在Talk()
的作用域中声明的另一个变量。不是类属性。
让它成为一个类属性:
class MyClass {
public $say = 'Something';
public function Talk() {
return $this->say;
}
}
$inst = new MyClass();
$said = 'He ' . $inst->say;
这违背了Talk()
的目的。
最后一行应该是$said = 'He '. $inst->Talk();
$say
不是一个类属性。如果是的话,你可以这样定义你的类:
class MyClass {
public $say;
}
它是函数Talk()
的一个局部变量。如果您想按照定义类的方式访问它,您可以这样做:
$instance = new MyClass();
$instance->Talk();
你需要让$Say成为MyClass类的一个即时变量。
class MyClass {
public $Say
public function Talk() {
$this->Say = "Something";
return $this->Say;
}
}
可以从类外部通过说本月->
此外,封装类实例变量并使用"getter"方法检索值是更好的实践。
class MyClass {
private $Say
public function Talk() {
$this->Say = "Something";
return $this->Say;
}
public getSay() {
return $this->Say;
}
}
$Inst = new MyClass();
echo $Inst->getSay();
oop的最佳实践是永远不要在你的类中使用公共属性。操作类属性的最佳方法是使用单独的方法来返回属性的值并设置属性的值。所以
class MyClass {
private $say;
// common setter, invoked when we trying to set properties as they are public
public function __set($name, $value) {
$methodname = 'set' . ucfirst(strtolower($name));
if (method_exists($this, $methodname)) {
$this->$methodname($value);
} else {
throw new Exception ('There is no "' . $name . '" property in "' . __CLASS__ . '" class');
}
}
// common getter, invoked when we trying to get properties as they are public
public function __get($name) {
$methodname = 'get' . ucfirst(strtolower($name));
if (method_exists($this, $methodname)) {
return $this->$methodname();
} else {
throw new Exception ('There is no "' . $name . '" property in "' . __CLASS__ . '" class');
}
}
// setter for out private property $say, invoked by common setter when colling $a->say = "something";
public function setSay($value) {
$this->say = $value;
}
// getter for out private property $say, invoked by common getter when colling $a->say;
public function getSay() {
return $this->say;
}
public function Talk($monologue) {
$this->say = (!empty($monologue))?$this->say:$monologue;
return $this->say;
}
}
所以现在你可以访问你的私有属性,因为它们是公共的,并做所有必要的检查,以避免在其中存储坏值。像这样:
$a = new MyClass;
$a->say = "Hello my friends !";
$a->Talk();
$a->Talk("Good bye !");
echo $a->say;
或者像这样:
$a = new MyClass;
$a->setSay("Hello my friends !");
$a->Talk();
$a->Talk("Good bye !");
echo $a->getSay();
为了更安全,您可以将setSay和getSay方法设为私有,但这样第二段代码就不能工作了。
你需要在你的函数之前声明var,例如
class MyClass {
public $say;
function Talk() {
$this->say = "something";
}
}
和
$Said = "He ".$Inst->$say;
可以使用
$said = "He" . $Inst->Talk();
,或者可以类
class MyClass {
var $say;
public function Talk() {
$say = "Something";
$this->say = $say;
return $say;
}
}
和
$said = "He" . $Inst->say;