PHP 面向对象基础:静态方法 static
什么是静态方法?
声明类方法为静态,就可以不实例化类而直接访问,修饰符为 static 。静态方法可以通过自身类和对象调用。因为静态方法不需要通过对象即可调用,所以伪变量 $this 在静态方法中不能被使用。
<?php
class MyTest
{
    public $a = 'five';
    public static function printStatic()
    {
        echo "Called static funtion" . "<br />";
    }
    public static function callThis()
    {
        $this->printStatic();
    }
    public static function printEverything()
    {
        self::printStatic();
    }
}通过类自身调用
// 输出 Called static funtion
MyTest::printStatic();也可以通过对象调用
$test = new MyTest();
// 输出 Called static funtion
$test::printStatic();不能在静态方法中使用 $this
// 报错 Fatal error: Uncaught Error: Using $this when not in object context
$test::callThis();但可以使用关键字 self 在静态方法类部调用其它静态方法, self 在这里代表类自身。
// 输出 Called static funtion
$test::printEverything(); 
           PHP 社区 Wiki
 PHP 社区 Wiki
     
             
             
             关于 LearnKu
                关于 LearnKu
               
                     
                     
                     粤公网安备 44030502004330号
 粤公网安备 44030502004330号 
 
推荐文章: