【发布时间】:2012-05-05 16:02:14
【问题描述】:
我不太擅长这个,所以我敢肯定这是一个愚蠢的问题。
我有一堂课:
class debug {
private static $messages = array();
private static $errors = array();
private static $all = array(); // includes both of above
private static $types = array('messages','errors');
public static function add($type, $message) {
if(!in_array($type,self::$types) ) {
self::add('errors','Bad type "' . $type . '" specified when sending this message: ' . $message);
return false;
}
self::$$type[] = $message; // ERROR IS HERE (see below)
self::$all[] = $message; // no error
}
}
我从另一个类中调用它以进行调试(惊喜)。
debug::add('error', 'Error in ' . __FILE__ . ' on line ' . __LINE__);
来自 error.log 的 PHP 错误消息:
PHP 致命错误:无法使用 [] 在第 1248 行读取 /var/www/lib/lib.php
它指的是调试类中的上述指定行。
编辑:
我想要做的是使用变量变量(因此是发布标题)来确定要向哪个静态数组添加数据。
即如果 $type == 'messages',则 $$type == $messages。
所以我想要 self::$$type[] == self::$messages[]
或者如果 $type == 'errors',那么 $$type == $errors 和 self::$$type[] == self::$errors[]
【问题讨论】:
-
您有错误数组,但您将其添加到错误数组中。
-
在您的情况下 $types 是一个数组,索引 $types[] 未设置,但您正尝试将其用作变量。当然这是错误的。您能解释一下您打算实现的目标吗?
-
@tpaksu,说得好,但你看我的 if(!in_array(...)) 应该解决这个问题。
-
是的,只是想说我看到了什么。
标签: php arrays class static-methods variable-variables