Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a static property of an instance

If I have an instance in PHP, what's the easiest way to get to a static property ('class variable') of that instance ?

This

$classvars=get_class_vars(get_class($thing));
$property=$classvars['property'];

Sound really overdone. I would expect

$thing::property

or

$thing->property

EDIT: this is an old question. There are more obvious ways to do this in newer PHP, search below.

like image 838
commonpike Avatar asked Apr 11 '11 15:04

commonpike


People also ask

What is static property?

Static properties are used when we'd like to store class-level data, also not bound to an instance. The syntax is: class MyClass { static property = ...; static method() { ... } } Technically, static declaration is the same as assigning to the class itself: MyClass.

What is a static property C#?

In C#, static means something which cannot be instantiated. You cannot create an object of a static class and cannot access static members using an object. C# classes, variables, methods, properties, operators, events, and constructors can be defined as static using the static modifier keyword.

What is a static property in JavaScript?

The static keyword defines a static method or property for a class, or a class static initialization block (see the link for more information about this usage). Neither static methods nor static properties can be called on instances of the class. Instead, they're called on the class itself.


2 Answers

You need to lookup the class name first:

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

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

like image 109
halfdan Avatar answered Sep 23 '22 07:09

halfdan


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"
like image 24
appcropolis Avatar answered Sep 22 '22 07:09

appcropolis