When to use $this->property instead of $property in PHP

前端 未结 5 936
轮回少年
轮回少年 2020-12-18 09:32

Super easy question. Look at the 2 sample class methods.

In the first One I pass in a variable/property call $params I then do $this->params

5条回答
  •  Happy的楠姐
    2020-12-18 10:04

    Your own theory

    You have to set it like $this->params if you need to access that property in a different method in that class and you can use just $params if you are only using that property in that same method it is in already.

    is a good guideline, but it falls somewhat short. Consider

    public function applyDiscount($discount)
    {
        if ($this->isValidDiscountRangeForProduct($discount)) {
            $this->price -= $this->price * $discount;
        }
    }
    

    You would not assign $discount to an object property just because you needed to validate it before applying it to the $this->price (use in other method). A better guideline would be

    If the argument is only used to calculate internal state of the object, you don't make it a property.

    Also, keep in mind that a method like your

    public function TestFunc2($params)
    {
       echo 'testing this something' . $params;
    }
    

    is likely misplaced on that object because it has no cohesion. You only want methods on your object that operate on the data of this object in some way. Attaching methods that do not operate on the object members is like tucking an ice crusher onto your car:

    class Car 
    {
        public function crushIce($ice)
        {
            // WTF!?
        }
    }
    

    Further resources:

    • https://en.wikipedia.org/wiki/Law_of_Demeter
    • https://en.wikipedia.org/wiki/GRASP_%28object-oriented_design%29
    • https://en.wikipedia.org/wiki/Solid_%28object-oriented_design%29

提交回复
热议问题