我知道在类中,$this
用于引用当前对象,self
用于引用当前类。例如:
class My_Class {
function start1() {
$var = self::hello();
echo $var;
}
function start2() {
$var = $this->hello();
echo $var;
}
function hello() {
return 'Hello';
}
}
$obj = new My_Class;
$obj->start1(); // Hello
$obj->start2(); // Hello
在我的示例中,$this->hello()
和self::hello()
似乎完全相同。任何人都可以举例说明我应该何时使用$this
以及何时使用self
?
答案 0 :(得分:1)
$this
不能用于静态函数。
$this
需要一个实例化对象。
class example
{
public static $mystring ;
public $anotherString;
//non-static functions (calling static and non-static variables)
public function regularFunction() { echo $this->anotherString; }
public function regularFnUsingStaticVar() { echo self::$mystring ; }
//static functions (calling static functions and variables)
public static function anotherStatFn() { self::staticFunction(); }
public static function staticFunction() { echo self::$mystring ; }
}
// using static vars and functions
example::$mystring = "Hello World!";
example::staticFunction(); /* Hello World! */
// using non-static vars and functions
$obj = new example();
$obj->anotherString = "Hello World!";
$obj->regularFunction(); /* Hello World! */