在PHP5中,使用self
和$this
有什么不同
什么时候是合适的?
发布于 2013-05-08 14:59:00
在类定义中,$this
指的是当前对象,而self
指的是当前类。
有必要使用self
引用类元素,使用$this
引用对象元素。
self::STAT // refer to a constant value
self::$stat // static variable
$this->stat // refer to an object variable
发布于 2009-05-18 19:42:36
我认为问题不在于是否可以通过调用ClassName::staticMember
来调用类的静态成员。问题是使用self::classmember
和$this->classmember
有什么不同。
例如,无论您使用self::
还是$this->
,以下两个示例都可以正常工作
class Person{
private $name;
private $address;
public function __construct($new_name,$new_address){
$this->name = $new_name;
$this->address = $new_address;
}
}
class Person{
private $name;
private $address;
public function __construct($new_name,$new_address){
self::$name = $new_name;
self::$address = $new_address;
}
}
发布于 2016-01-01 14:36:43
self
指的是当前类(在其中被调用),
$this
指的是当前对象。您可以使用static而不是self。
请参见示例:
class ParentClass {
function test() {
self::which(); // Outputs 'parent'
$this->which(); // Outputs 'child'
}
function which() {
echo 'parent';
}
}
class ChildClass extends ParentClass {
function which() {
echo 'child';
}
}
$obj = new ChildClass();
$obj->test();
输出:
parent
child
https://stackoverflow.com/questions/151969
复制相似问题