0

How do I get the following code not to blow up in my face?

<?php 

    class abc{
    }
    abc::$someDynamicVariable
?>

I don't really want to declare the variable before hand, and was hoping I could declare it in the __construct function ( javascript functions' arguments array anyone? )

The error I get is:

Fatal error: Access to undeclared static property: abc::$someDynamicVariable in

Alex
  • 5,674
  • 7
  • 42
  • 65
  • You definitely should declare it explictly within the class... – KingCrunch Jul 11 '12 at 21:18
  • It's for a sql factory that gets a config object, and I wanna autoload it based off the name of the variable I'm passing, as I have a few dbs i need to juggle ( and I want something I can use later on in my life ), so knowing what the variable is called is a problem. – Alex Jul 11 '12 at 21:21

2 Answers2

1

You dont have to give it a value right away:

class abc{
    public static $theVariable;

    // only give it a value when initialized 
    public function __construct() {
       $this->theVariable = "someValue"
    }
}
abc::$someDynamicVariable

or you can extend it with a different class

class abc{
    public static $theVariable;
}

extend

class cab extends abc {
   public function __construct() {
       $this->theVariable = "someValue"
   }
}
Ibu
  • 42,752
  • 13
  • 76
  • 103
  • This is wrong. You are using `$this` in conjunction to a static property. That should be `self::$theVariable` or `static::$theVariable` for late static binding. – fdomig Jul 11 '12 at 21:29
1

You may use PHPs Magic Methods __set()and __get() to set/get properties dynamic which do not exist so far.

Here is an example:

class Foo {
    private $data = array();

    public function __set($key, $value) {
        $this->data[$key] = $value;
    }

    public function __get($key) {
        return $this->data[$key];
    }
}

$foo = new Foo();
$foo->something = "bla"; // using magic __set()

echo $foo->something; // using magic __get()
fdomig
  • 4,417
  • 3
  • 26
  • 39
  • This doesn't work in a static context, as per https://bugs.php.net/bug.php?id=39678 – Alex Jul 11 '12 at 21:44
  • That's why this is not done in a staic context. However, adding properties to a class (not an object) might be done with `Reflection`. – fdomig Jul 11 '12 at 21:47