【问题标题】:When to use $this->property instead of $property in PHP何时在 PHP 中使用 $this->property 而不是 $property
【发布时间】:2011-12-08 08:51:35
【问题描述】:

超级简单的问题。查看 2 个示例类方法。

在第一个中,我传入一个变量/属性调用$params,然后我执行$this->params

我的问题是,它真的需要吗,我通常这样做,但我注意到它可以在第二个示例中使用,只需调用 $params 而不设置 $this

所以我的理论是这样...如果您需要在该类中以不同的方法访问该属性,则必须将其设置为 $this->params,如果您仅在它已经在使用相同的方法。

有人可以对此有所了解并解释我的理论是否正确或者我是否离题我想知道这样做的原因,以便我知道什么时候做每种方法或做一个或另一个时间,谢谢你

class TestClass{

    public function TestFunc($params){
       $this->params = $params;

       echo 'testing this something'. $this->params;
    }
}

不定义变量

class TestClass2{

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

【问题讨论】:

  • 您在第一个函数中所做的是读取传递给函数的参数,并将它们保存到类变量中。如果像示例中那样使用它是没有意义的,但是如果你想存储变量,那么这就是“设置函数”的工作方式

标签: php oop


【解决方案1】:

访问类变量时使用$this

当访问一个实际上是函数参数的变量时,不需要使用$this关键字。实际上,要访问名为$params的函数参数,你不应该使用$this关键字...

在你的例子中:

class TestClass{

    public function TestFunc($params){
       $this->params = $params;

       echo 'testing this something'. $this->params;
    }
}

来自TestFunc($params){$params 是函数TestFunc 的参数/参数,因此您不需要使用$this。事实上,要访问参数的值,你一定不能使用$this -- 现在当你从$this->params = $params = $params; 使用$this->params 时,你实际上是在设置一个与参数 @ 相同的值987654331@ 到一个名为 also $params 的新类级变量(因为您没有在示例代码中的任何地方声明它)

[编辑] 基于评论:

看这个例子:

class TestClass{

    public function TestFunc($params){
       $this->params = $params;
       # ^ you are setting a new class-level variable $params
       # with the value passed to the function TestFunc 
       # also named $params

       echo 'testing this something'. $this->params;
    }

    public function EchoParameterFromFunction_TestFunc() {
        echo "\n\$this->params: " . $this->params . "\n";
        # now you are echo-ing the class-level variable named $params
        # from which its value was taken from the parameter passed
        # to function TestFunc
    }

}

$tc = new TestClass();
$tc->EchoParameterFromFunction_TestFunc(); # error: undefined property TestClass::$params
$tc->TestFunc('TestFuncParam');
$tc->EchoParameterFromFunction_TestFunc(); # should echo: $this->params: TestFuncParam

在没有先调用TestFunc 的情况下调用EchoParameterFromFunction_TestFunc 时出现的错误是由于未声明/设置名为$params 的类级变量/属性——你在TestFunc 中设置了它,这意味着它除非您致电 TestFunc,否则不会设置。正确设置它以便任何人都可以立即访问它是:

class TestClass{
    # declare (and set if you like)
    public /*or private or protected*/ $params; // = ''; or create a construct...

    public function __construct(){
        # set (and first declare if you like)
        $this->params = 'default value';
    }
...
...
...

[编辑:附加]

正如 @liquorvicar 所提到的,我也完全同意的是,您应该始终声明所有类级别的属性/变量,无论您是否会使用它们。例如,原因是您不想访问尚未设置的变量。请参阅上面的示例,该示例引发了错误 undefined property TestClass::$params..

感谢@liquorvicar 提醒我..

【讨论】:

  • 所以如果另一个函数也需要一个函数参数,那么我就必须使用 $this->$param 对吗?
  • 如果你使用 $this->var 那么你可以在同一个类的所有方法中访问这个变量(比如这个类中的“global”)。
  • 可能值得补充的是,您应该声明所有类属性(并且您并没有真正向 OP 解释该术语)。
  • @jasondavis,请查看更新后的帖子。正如liquevicar 所说,您应该声明所有类级别的属性。 :)
  • 谢谢,我有个好主意,现在我确定了。我以前实际上用$this-> 声明我的所有属性,现在只用类变量来做更有意义
【解决方案2】:

我希望这将有助于解决问题:

class Person {

   private $name;
   private $age;

   public function __construct($name, $age){
     // save func params to instance vars
     $this->name = $name;
     $this->age = $age;
   }

   public function say_hello(){ // look, no func params!
     echo "My name is {$this->name} and I am {$this->age} years old!";
   }

   public function celebrate_birthday(){ // no params again
     echo "Party time!";
     $this->age += 1; // update instance var
     $this->drink_beer();  // call instance method
   }

   public function drink_beer(){
     echo "Beer is good!";
   }
}

$p = new Person("Sample", "20");
$p->say_hello();          // My name is Sample and I am 20 years old!
$p->celebrate_birthday(); // Party time! Beer is good!
$p->say_hello();          // My name is Sample and I am 21 years old!

【讨论】:

    【解决方案3】:

    一般而言,当特定变量位于对象的上下文(“范围”)中时,您可以使用它们。

    在 OOP 编程中,$this 几乎总是用于访问类变量或其他类方法。

    class MyClass{
         private $myNum;
    
         public function myFunc(){
              echo 'My number is '.$this->myNum; // Outputting the class variable "myNum"
         }
    
         public function go($myNumber){
              $this->myNum  = $myNumber; // Will set the class variable "$myNum" to the value of "$myNumbe" - a parameter fo the "go" function.
              $this->myFunc(); // Will call the function "myFunc()" on the current object
         }
    }
    

    夏。

    【讨论】:

      【解决方案4】:

      您已经自己回答了您的问题:

      如果你需要访问它,你必须将它设置为 $this->params 该类中不同方法中的属性,您可以只使用 $params 如果您仅在相同的方法中使用该属性 已经在

      【讨论】:

        【解决方案5】:

        你自己的理论

        如果您需要在该类中以不同的方法访问该属性,则必须将其设置为 $this->params,如果您仅在其已存在的相同方法中使用该属性,则可以仅使用 $params

        是一个很好的指南,但它有些不足。考虑

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

        您不会将$discount 分配给对象属性,因为您需要在将其应用于$this->price 之前对其进行验证(在其他方法中使用)。一个更好的指导方针是

        如果参数仅用于计算对象的内部状态,则不要将其设为属性。

        另外,请记住,像您的方法

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

        很可能在那个对象上放错了位置,因为它没有内聚力。您只需要对象上的方法以某种方式对该对象的数据进行操作。附加对对象成员不起作用的方法就像将碎冰机塞到您的汽车上:

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

        更多资源:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-09
          • 2023-04-05
          • 2012-04-19
          • 1970-01-01
          • 2016-03-17
          相关资源
          最近更新 更多