我继承了一些 php 5.x 代码,这些代码在 php 7.4.3 上发出以下警告:
PHP Warning: Use of undefined constant self - assumed 'self'
(this will throw an Error in a future version of PHP)
有问题的行在这里:
class Array_sort
{
static private $key;
static private $type = 'ASC';
public static function sort_by_key($array, $key, $type = 'ASC') {
self::$key = $key;
self::$type = $type;
usort($array, array(self,'sort_by')); //<-- offending use of 'self'
return $array;
}
private static function sort_by($a, $b) {
if ($a == $b)
return 0;
// other comparisons omitted but result in 1 or -1 being returned
}
}
我不确定 self 在对 usort 的调用中试图引用什么。
感谢任何指点。谢谢。
最佳答案
使用self
来引用当前类。不是类名。
尝试使用魔法常量:
if(isset($user->$name) || property_exists(__CLASS__, $name)){
来自 php 手册:__CLASS__
类名。 (在 PHP 4.3.0 中添加)从 PHP 5 开始,此常量返 echo 明时的类名(区分大小写)。在 PHP 4 中,它的值始终是小写的。类名包括声明它的 namespace (例如 Foo\Bar)。请注意,从 PHP 5.4 开始,CLASS 也适用于特征。当在特征方法中使用时,CLASS 是使用该特征的类的名称。
了解更多:
https://php.net/manual/en/language.constants.predefined.php
解决方案:
usort($array, array(__CLASS__,'sort_by'));
关于PHP警告: Use of undefined constant self - assumed 'self' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65056133/