2

When you have inherited classes, where the child class sets some constants and the parent class has a static method that needs to use them:

class some_helperclass {

    public static function add_them() {

        return self::some_c + self::another_c;
    }

}    

class mainclass extends some_helperclass {

    const some_c  = 1;
    const another_c  = 2;

}

I get an error when I try to execute this:

mainclass::add_them()

Is there a way to get this to work?

1
  • 2
    "an error" - well, that's not very specific. Wanna tell anyone, or maybe google it yourself? Commented Feb 19, 2017 at 23:17

1 Answer 1

3

This is a good example of how late static binding works.

I won't rewrite the documentation for it, but the TL;DR is that self refers to the literal class that executes the code. In your example it's mainclass that defines the constants, but some_helperclass that reads them so it doesn't work using self.

If you change to use static::CONST_NAME it will work.

Also - it's good practice to name constants in upper case only.

Code example:

<?php

class some_helperclass {

public static function add_them() {

    return static::some_c + static::another_c;
    }

}    

class mainclass extends some_helperclass {

    const some_c  = 1;
    const another_c  = 2;

}

var_dump(mainclass::add_them());

Output: int(3)

Sign up to request clarification or add additional context in comments.

3 Comments

eval.in was throwing (internal) server errors (an error on their end I'm sure). I edited
Thanks Fred- it does that sometimes :-)
Great! Thank you both for your help. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.