在PHP5中,使用self和$this有什么区别?
什么时候合适?
在PHP5中,使用self和$this有什么区别?
什么时候合适?
当前回答
关键字self不仅仅指“当前类”,至少不会限制静态成员。在非静态成员的上下文中,self还提供了一种绕过当前对象的vtable(参见vtable上的wiki)的方法。正如您可以使用parent::methodName()调用函数的父版本一样,您也可以调用self::methodName)调用方法的当前类实现。
class Person {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function getTitle() {
return $this->getName()." the person";
}
public function sayHello() {
echo "Hello, I'm ".$this->getTitle()."<br/>";
}
public function sayGoodbye() {
echo "Goodbye from ".self::getTitle()."<br/>";
}
}
class Geek extends Person {
public function __construct($name) {
parent::__construct($name);
}
public function getTitle() {
return $this->getName()." the geek";
}
}
$geekObj = new Geek("Ludwig");
$geekObj->sayHello();
$geekObj->sayGoodbye();
这将输出:
你好,我是极客路德维希路德维希再见了
sayHello()使用$this指针,因此调用vtable调用Geek::getTitle()。sayGoodbye()使用self::getTitle(),因此不使用vtable,而是调用Person::getTitle()。在这两种情况下,我们都在处理实例化对象的方法,并且可以访问调用函数中的$this指针。
其他回答
我遇到了同样的问题,简单的答案是:
$这需要类的实例self::不
每当您使用静态方法或静态属性并希望在没有实例化类对象的情况下调用它们时,都需要使用self:来调用它们,因为$this总是需要创建一个对象。
此外,由于$this::尚未讨论。
仅供参考,从PHP 5.3开始,当处理实例化对象以获取当前作用域值时,与使用static::不同,可以选择使用$this::这样。
http://ideone.com/7etRHy
class Foo
{
const NAME = 'Foo';
//Always Foo::NAME (Foo) due to self
protected static $staticName = self::NAME;
public function __construct()
{
echo $this::NAME;
}
public function getStaticName()
{
echo $this::$staticName;
}
}
class Bar extends Foo
{
const NAME = 'FooBar';
/**
* override getStaticName to output Bar::NAME
*/
public function getStaticName()
{
$this::$staticName = $this::NAME;
parent::getStaticName();
}
}
$foo = new Foo; //outputs Foo
$bar = new Bar; //outputs FooBar
$foo->getStaticName(); //outputs Foo
$bar->getStaticName(); //outputs FooBar
$foo->getStaticName(); //outputs FooBar
使用上面的代码不是常见的或推荐的做法,只是为了说明它的用法,在引用原海报的问题时更像是“你知道吗?”。
它还表示$object::CONSTANT的用法,例如echo$foo::NAME;与$this::NAME相反;
从这篇博客文章:
self指当前类self可用于调用静态函数和引用静态成员变量self可以在静态函数中使用self还可以通过绕过vtable来关闭多态行为$这是指当前对象$this可用于调用静态函数$this不应用于调用静态成员变量。改用self。$this不能在静态函数中使用
我认为问题不在于是否可以通过调用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;
}
}
在类定义中,$this引用当前对象,而self引用当前类。
必须使用self引用类元素,并使用$this引用对象元素。
self::STAT // refer to a constant value
self::$stat // static variable
$this->stat // refer to an object variable