Get a static property of an instance

You need to lookup the class name first:

$class = get_class($thing);
$class::$property

$property must be defined as static and public of course.


From inside a class instance you can simply use self::...

class Person {
  public static $name = 'Joe';
  public function iam() {
    echo 'My name is ' . self::$name;
  }
}

$me = new Person();
$me->iam(); // displays "My name is Joe"

If you'd rather not

$class = get_class($instance);
$var = $class::$staticvar;

because you find its two lines too long, you have other options available:

1. Write a getter

<?php
class C {
  static $staticvar = "STATIC";
  function getTheStaticVar() {
    return self::$staticvar;
  }
}
$instance = new C();
echo $instance->getTheStaticVar();

Simple and elegant, but you'd have to write a getter for every static variable you're accessing.

2. Write a universal static-getter

<?php
class C {
  static $staticvar = "STATIC";
  function getStatic($staticname) {
    return self::$$staticname;
  }
}
$instance = new C();
echo $instance->getStatic('staticvar');

This will let you access any static, though it's still a bit long-winded.

3. Write a magic method

class C {
  static $staticvar = "STATIC";
  function __get($staticname) {
    return self::$$staticname;
  }
}
$instance = new C();
echo $instance->staticvar;

This one allows you instanced access to any static variable as if it were a local variable of the object, but it may be considered an unholy abomination.