1

trying to understand something. I have a Config class where I define a load of constants. In one of my other classes, I need to use one of the constants from Config. So I start off by using the class

use \CONFIG\Config;

In my class constructor, I then assign the class to a variable

public function __construct() {
    $config = new Config;
}

In the consturctor, I can then get access to a constant by doing something like this

$config::BASE_PATH;

So I dont seem to get any complaints when doing this. If I create a class variable though, and change my constructor to the following

public function __construct() {
    $this->config = new Config;
    $this->config::BASE_PATH;
}

It complains that it is using an incorrect access to a static class member.

Why does it seem to work as a local variable, but not as a class variable?

Thanks

Jens A. Koch
  • 39,862
  • 13
  • 113
  • 141
katie hudson
  • 2,765
  • 13
  • 50
  • 93
  • Huh. `::` is not listed on the operator precedence page at php.net. My guess is that the scope resolution is happening before the `->` is applied. – Jerry Nov 12 '15 at 17:23
  • Possible duplicate of [Accessing PHP Class Constants](http://stackoverflow.com/questions/5447541/accessing-php-class-constants) – Jens A. Koch Nov 13 '15 at 23:56

1 Answers1

1

The issue is not related to Composer. Its a syntax problem of PHP, while accessing class constants.

The syntax $this->myclass::CONSTANT to access a class constant is not supported in PHP version below PHP 7.

DEMO

<?php
class MyClass
{
    const CONSTANT = 'constant value';

    function showConstant() {
        echo  self::CONSTANT . "\n";
    }
}

echo MyClass::CONSTANT . "\n";

$classname = "MyClass";
echo $classname::CONSTANT . "\n"; // As of PHP 5.3.0

class B 
{
   function __construct()
   {
       $this->myclass = new MyClass();
       $this->myclass->showConstant();

       /**
        * #### This will not work in PHP Version below PHP 7! ####
        */
       echo $this->myclass::CONSTANT;
   }
}

$b = new B;
?>
Jens A. Koch
  • 39,862
  • 13
  • 113
  • 141