从存储在另一个类中的实例访问类常量 [英] Accessing class constants from instance stored in another class

查看:272
本文介绍了从存储在另一个类中的实例访问类常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定义的类,它有几个常量定义通过`const FIRST ='something';

I have a class defined which has several constants defined through `const FIRST = 'something';

我已经实例化类 $ class = new MyClass()

然后我有另一个类需要一个 MyClass 实例作为其构造函数参数之一,并将其​​存储为 $ this-> model = $ myClassInstance;

then I have another class that takes a MyClass instance as one of it's constructors parameters and stores it as $this->model = $myClassInstance;

工作正常。

但我想知道如何从该实例访问常量。

But I am wondering how I can access the constants from that instance?

$ this-> model :: STATE_PROCESSING 但我的IDE告诉我


访问静态类成员。

Incorrect access to static class member.

PHP告诉我


意外的'::'(T_PAAMAYIM_NEKUDOTAYIM)在...

unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM) in ...

我知道我可以做 MyClass :: STATE_PROCESSING 但我想知道是否有一种方法来获得他们基于实例?

I know I can do MyClass::STATE_PROCESSING but I am wondering if there is a way to get them based off the instance?

推荐答案

看起来像您的旧版本的php? PHP 5.3允许以你描述的方式访问常量...但是,这是如何没有固有的能力:

Seems like your on an older version of php? PHP 5.3 allows the access of constants in the manner you describe... However, this is how you can do it without that inherent ability:

class ThisClass
{
    const FIRST = 'hey';

    public function getFIRST()
    {
        return self::FIRST;
    }
}

class ThatClass
{
    private $model;

    public function setModel(ThisClass $model)
    {
        $this->model = $model;
    }

    public function getModel()
    {
        return $this->model;
    }

    public function Hailwood()
    {
        $test = $this->model;
        return $test::FIRST;
    }
}

$Class = new ThisClass();
echo $Class->getFIRST(); //returns: hey
echo $Class::FIRST; //returns: hey; PHP >= 5.3

// Edit: Based on OP's comments
$Class2 = new ThatClass();
$Class2->setModel($Class);
echo $Class2->getModel()->getFIRST(); //returns: hey
echo $Class2->Hailwood(); //returns: hey

基本上,创建一个getter函数来访问常量。

Basically, were creating a 'getter' function to access the constant. The same way you would to externally access private variables.

请参阅OOP类常量文档: http://php.net/manual/en/language.oop5.constants.php

See the OOP Class Constants Docs: http://php.net/manual/en/language.oop5.constants.php

这篇关于从存储在另一个类中的实例访问类常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆