Do child classes inherit parent constants and if so how do I access them?

You can also access to constant define in children from parent method, with the static key.

<?php

class Foo {

    public function bar() {

        var_dump(static::A);
    }
}

class Baz extends Foo {

    const A = 'FooBarBaz';

    public function __construct() {

        $this->bar();
    }
}

new Baz;

I think you would need to access it like this:

self::CONSTANT_1;

or alternatively "parent", which will always be the value established in the parent class (i.e., the constant's immutability is maintained):

parent::CONSTANT_1;

Interesting

One thing that is interesting to note is that you can actually override the const value in your child class.

class MyParentClass{

    const CONSTANT_1=1;
}

class MyChildClass extends MyParentClass{

    const CONSTANT_1=2;
}

echo MyParentClass::CONSTANT_1; // outputs 1
echo MyChildClass::CONSTANT_1; // outputs 2

You do not have to use parent. You can use self which would first check if there is constant with the same name in the class itself, then it would try to access the parents constant.

So self is more versatile and provides the possibility to 'overwrite' the parents constant, without actually overwriting it as you can still explicitly access it via parent::.

Following structure:

<?php

class parentClass {

    const MY_CONST = 12;

}

class childClass extends parentClass {

    public function getConst() {
        return self::MY_CONST;
    }

    public function getParentConst() {
        return parent::MY_CONST;
    }

}

class otherChild extends parentClass {

    const MY_CONST = 200;

    public function getConst() {
        return self::MY_CONST;
    }

    public function getParentConst() {
        return parent::MY_CONST;
    }
}

Leads to the following results:

$childClass = new childClass();
$otherChild = new otherChild();


echo childClass::MY_CONST; // 12
echo otherChild::MY_CONST; // 200

echo $childClass->getConst(); // 12
echo $otherChild->getConst(); // 200

echo $childClass->getParentConst(); // 12
echo $otherChild->getParentConst(); // 12

Tags:

Php

Oop

Class