Gio*_*gio 2 php methods global-variables
几天前我开始用PHP编写新课程.
我想在其他方法中使用的方法中声明一个新的"公共属性".
这就是我的想法(当然它不起作用!):
class hello {
public function b() {
public $c = 20; //I'd like to make $c usable by the method output()
}
public function output() {
echo $c;
}
}
$new = new hello;
$new->output();
Run Code Online (Sandbox Code Playgroud)
提前感谢任何提示.
我想在其他方法中使用的方法中声明一个新的"公共属性".
如果其他方法属于同一个类,则不需要公共属性,私有属性将满足您的需求.私有属性只能在同一个类中访问,这有助于简化操作.
还要了解声明属性和为其赋值的区别.加载代码时进行声明,并在执行时进行分配.因此,声明(或定义)属性(私有或公共)需要PHP语法中的特殊位置,即在类的主体中而不是在函数内部.
您可以使用$thisPHP中的特殊变量访问类中的属性.
$this从对象上下文中调用方法时,伪变量可用.$this是对调用对象的引用(通常是方法所属的对象[to]).从PHP手册
私有财产示例:
class hello {
private $c; # properties defined like this have the value NULL by default
public function b() {
$this->c = 20; # assign the value 20 to private property $c
}
public function output() {
echo $this->c; # access private property $c
}
}
$new = new hello;
$new->output(); # NULL
$new->b();
$new->output(); # 20
Run Code Online (Sandbox Code Playgroud)
希望这是有帮助的.您使用私有属性,因为程序中的其他所有内容都不需要关心它,因此在您的类中,您知道没有其他任何东西可以操纵该值.见以及能见度文档.