static 关键字用来修饰属性、方法,称这些属性、方法为静态属性、静态方法。
在类的静态方法中是不能直接以$this->test()的方式调用非静态方法的。还有框架中静态的调用非静态方法是怎么回事???
。。。
算了,不知道说啥
具体为啥看代码注释:
<?php
class Pay
{
public function bike()
{
return 'I\'m going out on my bike';
}
public static function selfDriveJourney()
{
// $this->bike(); // 这个样的写法会直接报错 Using $this when not in object context
// self::bike(); // self 在低版本 php 中可行,会自动将非静态方法转换为静态方法,在高版本的 PHP 中会报错 Non-static method App\\Services\\UploadFiles::saveFiles() should not be called statically
// ps:什么?你问我PHP版本到底多高多低?我只能告诉你,我也没测试具体版本,所以我不知道,自己去测试下吧
// 在高版本PHP中建议写法
return (new self())->bike();
}
protected function car()
{
return 'I\'m going to drive out and play';
}
/**
* static __callStatic 静态调用非静态的方法
* @param $method
* @param $arguments
* @return mixed
*/
public function __callStatic($method, $arguments)
{
return (new static())->$method(...$arguments);
}
}
echo Pay::selfDriveJourney(); // I'm going out on my bike
echo Pay::car(); // I'm going to drive out and play
最后说明下 car 方法为啥用 protected,不用 public。官方文档有说明,public 是一个公开的可访问方法,所以就不会走魔术方法 __callStatic 导致报错。