Search code examples
phparraysclassstatic-methodsvariable-variables

PHP Error when using variable variable to insert data into static variable


I'm not very good at this, so I'm sure this is a stupid question.

I have a class:

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
  }

}

I'm calling this from another class in order to debug (Surprise).

debug::add('error', 'Error in ' . __FILE__ . ' on line ' . __LINE__);

PHP error message from error.log:

PHP Fatal error: Cannot use [] for reading in /var/www/lib/lib.php on line 1248

It refers to the above-specified line in the debug class.

EDIT:

What I am trying to do is use a variable variable (hence the posting title) to determine which static array to add data to.

I.e. if $type == 'messages', then $$type == $messages.

So I want self::$$type[] == self::$messages[]

Or if $type == 'errors', then $$type == $errors and self::$$type[] == self::$errors[]


Solution

  • Change the following line to. This ensures that $type is evaluated into 'message' or 'error' first.

    self::${$type}[] = $message; 
    

    To expand on this, this is the code that I have. There seems to be additional syntax errors in your code that is causing the other failures, but this is why $$type[] is giving you that error.

    class debug {
        public static $messages = array();
        public static $errors = array();
        public static $all = array(); // includes both of above
        private static $types = array('messages','errors');
        public static function add($type, $message) {
            self::${$type}[] = $message;
            self::$all[] = $text;
        }
    }
    
    debug::add('messages', "Regular Message");
    debug::add('errors', "Error Message");
    
    print_r(debug::$messages);
    print_r(debug::$errors);
    

    And this is the output that I get

    Array
    (
        [0] => Regular Message
    )
    Array
    (
        [0] => Error Message
    )