I have a question regarding static function in php.

let's assume that I have a class

class test {
    public function sayHi() {
        echo 'hi';
    }
}

if I do test::sayHi(); it works without a problem.

class test {
    public static function sayHi() {
        echo 'hi';
    }
}

test::sayHi(); works as well.

What are the differences between first class and second class?

What is special about a static function?

推荐答案

In the first class, sayHi() is actually an instance method which you are calling as a static method and you get away with it because sayHi() never refers to $this.

Static functions are associated with the class, not an instance of the class. As such, $this is not available from a static context ($this isn't pointing to any object).

Php相关问答推荐

为什么注册SIGHUP的处理程序函数会阻止在PHP CLI中等待输入时点击X关闭Xterm窗口?""

make dd()如何正确工作?¨

WooCommerce:有条件地更改特定区域的发货类别

PHP中冒号的奇怪用例

按与WooCommerce管理顺序列表中的特定字符串不匹配的特定元值筛选订单

使用PHP编码的字符串与使用OpenSSL编写的shell 代码之间的差异

当配置的URL为空时禁用Laravel Slack日志(log)记录

可以';exec、system和shell_exec PHP函数中的命令字符串上的字符数不得超过8175

用ajax获取文件 - CORS问题&;设置缓存?

Shopware 6插件:由于删除了配置密钥,更新后配置值不正确

Symfony:从控制器内部调用自定义命令

WooCommerce:如果订单总数为零,则隐藏本地取货运输选项

有没有办法获取触发流操作的页面的 URI?

如何处理 Null 上的 array_shift() ?

将产品数量、名称和结帐链接添加到 WooCommerce 添加到购物车消息

PHP 合并/合并多维数组

php preg_match 验证 Tiktok 用户名

使用 PHP ImageMagick 库将 pdf 文件的前 n 页转换为单个 png 图像文件

如何在php中获取大于50的年龄

PHP获取根据辞职日期自动续订的合同终止日期