0

I need to access a constant that belongs to a class, but instead of writing the class' name explicitly, I want to retrieve it from the object directly. The object is a property of another object.

$this->fetcher::BASE_URL

This statement produces the error syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)

silkfire
  • 24,585
  • 15
  • 82
  • 105
  • possible duplicate of [Accessing PHP Class Constants](http://stackoverflow.com/questions/5447541/accessing-php-class-constants) – Rizier123 Feb 25 '15 at 22:20
  • Just a thought: `($this->fetcher)::BASE_URL` – rdiz Feb 25 '15 at 22:25
  • @Dencker Already tried that, gives error unfortunately... – silkfire Feb 25 '15 at 22:27
  • I think I recall that your initial syntax is actually possible in 5.6, although I'm not sure. If it's an option and you think it's worth it, you could try upgrading. – rdiz Feb 25 '15 at 22:49
  • Make it mandatory that $this->fetcher is an object that gives its own base url. IMO better solution. – Weltschmerz Feb 26 '15 at 00:07

2 Answers2

1

Here's an ugly work-around....

<?php
class simpleClass {
    public function __construct() {
        $this->fetcher = new simpleClass2();
    }

    public function printBaseURL() {
        $fetcher = $this->fetcher;
        print 'Base URL: ' . $fetcher::BaseUrl;
    }
}

class simpleClass2 {
    const BaseUrl = 'one';
}


$simpleClass = new simpleClass();

$simpleClass->printBaseURL();
Tango Bravo
  • 3,221
  • 3
  • 22
  • 44
0

You could use a function to return the constant

class MyClass
{
   function getConstant() {
       return  self::CONSTANT . "\n";
   }
}

Then call that function

$class = new MyClass();
$class->getConstant();

Or simply call the constant

MyClass::CONSTANT;

You can find more information about accessing constants within classes here. Look at the "user contributed notes", very good examples with explanation there.

André Ferraz
  • 1,511
  • 11
  • 29
  • I'd rather not use extra functions for something that should be achievable with basic language constructs. Is there some cleaner way? – silkfire Feb 25 '15 at 22:20