PHP警告: Use of undefined constant self - assumed 'self'

标签 php

我继承了一些 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/

相关文章:

php - Zend Form 和普通 HTML 表单之间的区别 Zend Framework

php - 我想在没有 flash 插件的情况下上传视频/大文件

php - 独立的 PHP 服务器

php - 使用 PHP 更新 MySql 中的多行

PHP 比较变量每次都返回 false

php - 如何将数组结果放入字符串中并回显它们

php - 带重音的记录上带有 "b"前缀的字符串

PHP 异步网络服务

PHP:为什么 ERROR 常量会产生错误?

php - Zencart 中的 session 问题