0

i came by some php code where the developer who wrote it is being a little contradictory i think. so here is the code he wrote:

if ($this->SQL !== null && $this->SQLState === self::STATE_CLEAN)
        return $this->SQL;

where the SQLState and the STATE_CLEAN are defined like this:

class someClass {
    const STATE_CLEAN = 1;
    private $SQLState = self::STATE_CLEAN;
}

so you can see that for some class attributes he uses $this and for some he uses self:: and i can't understand why. can any one help. Thanks

4
  • 2
    Possible duplicate of When to use self over $this?
    – Spoody
    Commented Apr 13, 2018 at 21:58
  • not possible because i know what they both mean, i just don't understand this specific case.
    – oajmi
    Commented Apr 13, 2018 at 22:00
  • Guess I don't understand your question then. Can you explain more?
    – Spoody
    Commented Apr 13, 2018 at 22:01
  • he is purposely using both self:: and $this while he can use $this instead, actually he should use none of the defined attributes are static? so i think either he is inconsistent with his code or he knows something i don't know
    – oajmi
    Commented Apr 13, 2018 at 22:04

2 Answers 2

3

Here:

private $SQLState = self::STATE_CLEAN;

The property is initialized to the value of the constant.

At some point, the property may change, but the constant is constant. So checking for this condition:

$this->SQLState === self::STATE_CLEAN

makes sense to verify that the current state is the same as the initial state.


To clarify since I think I missed the main point of the question, self::STATE_CLEAN is used because STATE_CLEAN is a class constant. Using $this->STATE_CLEAN will get you

Notice: Undefined property: someClass::$STATE_CLEAN

4
  • why not using $this->STATE_CLEAN instead of self::STATE_CLEAN
    – oajmi
    Commented Apr 13, 2018 at 22:06
  • @Dever In which part he should've used $this->STATE_CLEAN instead of self::STATE_CLEAN?
    – Spoody
    Commented Apr 13, 2018 at 22:12
  • both actually while none of them are static why using self::
    – oajmi
    Commented Apr 13, 2018 at 22:13
  • @Dever STATE_CLEAN is a constant, you can't access it using $this
    – Spoody
    Commented Apr 13, 2018 at 22:15
1

Good practice is to:

use self:: for class constants
(when refering class - you could have no initialized object instance of this class)

and $this-> for class variables
(when refering initialized object instance)

Not the answer you're looking for? Browse other questions tagged or ask your own question.