静态

静态类 属于 PHP

{other: "%{count} 个练习"}

关于 静态类

类在 PHP 中是一种代码组织单位,通常表示某个事物、服务或流程的实例。 借助static和self关键字,属性和方法可以归属于类本身,面向所有实例(也可以不依赖任何实例)。

<?php

class Book
{
    static $genre = 'Adventure';

    static function getGenre()
    {
        return self::$genre;
    }
}

// Usage
$genre = Book::$genre;
$genre = Book::getGenre();

限制

静态的类方法只能调用同一个类中的其他静态属性或静态方法。

<?php

class Book
{
    $name = 'Treasure Island';

    static function getName()
    {
        // This static method cannot access the instance variable
        return $this->name;
    }
}
通过 GitHub 编辑 该链接会在新窗口或标签页中打开