我什么时候应该使用 'self' 而不是 '$this'?

本教程将介绍我什么时候应该使用 'self' 而不是 '$this'?的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

我什么时候应该使用 'self' 而不是 '$this'? 教程 第1张

问题描述

In PHP 5, what is the difference between using self and $this?

When is each appropriate?

解决方案

Short Answer

Use $this to refer to the current
object. Use self to refer to the
current class. In other words, use
$this->member for non-static members,
use self::$member for static members.

Full Answer

Here is an example of correct usage of $this and self for non-static and static member variables:

<?php
class X {
 private $non_static_member = 1;
 private static $static_member = 2;

 function __construct() {
  echo $this->non_static_member . ' '
  . self::$static_member;
 }
}

new X();
?>

Here is an example of incorrect usage of $this and self for non-static and static member variables:

<?php
class X {
 private $non_static_member = 1;
 private static $static_member = 2;

 function __construct() {
  echo self::$non_static_member . ' '
  . $this->static_member;
 }
}

new X();
?>

Here is an example of polymorphism with $this for member functions:

<?php
class X {
 function foo() {
  echo 'X::foo()';
 }

 function bar() {
  $this->foo();
 }
}

class Y extends X {
 function foo() {
  echo 'Y::foo()';
 }
}

$x = new Y();
$x->bar();
?>

Here is an example of suppressing polymorphic behaviour by using self for member functions:

<?php
class X {
 function foo() {
  echo 'X::foo()';
 }

 function bar() {
  self::foo();
 }
}

class Y extends X {
 function foo() {
  echo 'Y::foo()';
 }
}

$x = new Y();
$x->bar();
?>

The idea is that $this->foo() calls the foo() member function of whatever is the exact type of the current object. If the object is of type X, it thus calls X::foo(). If the object is of type Y, it calls Y::foo(). But with self::foo(), X::foo() is always called.

From http://www.phpbuilder.com/board/showthread.php?t=10354489:

By http://board.phpbuilder.com/member.php?145249-laserlight

好了关于我什么时候应该使用 'self' 而不是 '$this'?的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。