简体   繁体   中英

How to access a constant from an object instead of its class?

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)

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM