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

oajmi
  • 187
  • 1
  • 1
  • 14
  • 2
    Possible duplicate of [When to use self over $this?](https://stackoverflow.com/questions/151969/when-to-use-self-over-this) – Spoody Apr 13 '18 at 21:58
  • not possible because i know what they both mean, i just don't understand this specific case. – oajmi Apr 13 '18 at 22:00
  • Guess I don't understand your question then. Can you explain more? – Spoody Apr 13 '18 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 Apr 13 '18 at 22:04

2 Answers2

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

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
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)

mu4ddi3
  • 135
  • 10