简体   繁体   English

如何从对象而不是其类访问常量?

[英]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) 该语句产生错误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. 查看“用户提供的注释”,那里是很好的示例,并带有说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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