PHP 面向对象基础:静态方法 static 1 个改进

什么是静态方法?

声明类方法为静态,就可以不实例化类而直接访问,修饰符为 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();
本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!