Question

I have two classes. Class B has field: object of class A (composition relationship). It is necessary to get static variable of class A. But there are some problems in code:

<?php
class A {
    public static $var = 'a';
}

class B {
    private $object;

    private function staticAccess($className) {
        $this->object = $className;
    }

    public function __construct() {
        $this->staticAccess('A');
        // This is wrong syntax:
        //$a = $this->object::$var;

        // Syntax which works but unconvenient
        $objA = $this->object;
        $a = $objA::$var;
    }
}

As you saw there is a solution. But it is necessary to write additional line. Is it possible to solve a task in one line?

Thanks you for any help!

Was it helpful?

Solution

It's not possible to do in one line (just a constraint of PHP). I'd suggest adding a function that you can use, something like this:

public function getStaticVar($var) {
    $class = new ReflectionClass($this->object);
    $value = $class->getStaticPropertyValue($var);

    return $value;
}

Using the Reflection library is the only way of dynamically accessing a dynamic static property in PHP.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top