Php - accessing constant through class instance in parent

Some code first ...

FlashBagUtil class containing constants:

class FlashBagUtil
{
    const TYPE_NOTICE  = 'notice';
    const TYPE_WARNING = 'warning';
    const TYPE_ALERT   = 'alert';
    const LANG_EN      = 'en';
    const LANG_RU      = 'ru';
    const LANG_IL      = 'il';
}

      

Parent class:

class CoreController
{
    public $flashUtil;

    public function __construct()
    {
        $this->flashUtil = new FlashBagUtil;
    }
}

      

Child class:

class BatchController extends CoreController
{
    public function indexAction()
    {
        // Method 1 - This works fine
        $flash     = $this->flashUtil;
        $flashType = $flash::TYPE_NOTICE;

        // Method 2 - This, obviously, does not
        $flashType = $this->flashUtil::TYPE_NOTICE;

        // Method 3 - Neither does this as $flashUtil is a non-static instantiated object
        $flashType = self::$flashUtil::TYPE_NOTICE;
    }
}

      

PHP states documentation : a property declared as static cannot be accessed by an instance object of the class (although a static method can be used).

But I seem to be able to do it with the first method. What am I missing?

+

Is method 1 the only and cleanest way to access static content in this context?

+3


source to share


3 answers


You are referring to the constant class , which is different from a class variable (property) and is available to the objects created. The documentation you link to is for a variable class defined by a keyword static

(i.e. private static $flashUtil;

), which can be a source of your confusion if you are used to programming in other strongly typed OOP languages.



+3


source


if you want to use your class as an enumeration, do the enumerationsclass reference:

abstract FlashBagUtil
{
    const TYPE_NOTICE = 'notice';
    ...
}

      



and use it in your child class:

class Controller
{
    private flashType = FlashBagUtil::TYPE_NOTICE;
}

      

0


source


Making it an abstract class as suggested would not be very useful here I think since there are more things going on in the FlashBagUtil class which I removed for the example code.

My method 1 works, but requires making a copy of the original object, which is not the purpose of the shared inherited object. So that...

I ended up setting up a standard way to directly access static content by importing the namespace into a child class and using $flashType = FlashBagUtil::TYPE_NOTICE

as suggested by Ralphael. It would be nice to be able to access constants from an object in the same liner, but this also preserves static content.

Full child class:

use TreasureForge\CoreBundle\Util\FlashBagUtil;

class BatchController extends CoreController
{
    public function indexAction()
    {
        $flash = FlashBagUtil::TYPE_NOTICE;
    }
}

      

Thanks a lot for your input.

0


source







All Articles