$ this和php中的简单变量之间的区别

时间:2014-03-17 17:58:34

标签: php class this

我不明白$this我们可以两种方式访问​​的重要性,即

class student
{
private:
        $myVar;
function set_Name($tmp_myVar){
                    $this $myVar=$tmp_myVar;
                }   
}

以及

class student
{
private:
        $myVar;
function set_Name($tmp_myVar){
                     $myVar=$tmp_myVar;
                }   
}

然后使用$this

的逻辑是什么

2 个答案:

答案 0 :(得分:2)

$this指的是当前对象的范围,而不是函数的局部范围。

例如:

class Student {
  private $screenname;

  public function __construct($name) {
    $this->screenname = $name; //object scope
  }

  public function say_my_name() {
    printf("My name is %s.\n", $this->screenname);
  }

  public function say_something_else($string) {
    $screenname = $string; //local scope
    printf("My name is %s, and I say '%s'.\n", $this->screenname, $screenname);
  }
}

$obj = new Student("Betty");
$obj->say_my_name();
//Output: My name is Betty.
$obj->say_something_else('Veronica');
//Output: My name is Betty and I say 'Veronica'.
$obj->say_my_name();
//Output: My name is Betty.

答案 1 :(得分:0)

class Student {
    public $screenName;

    public function getScreenName() {
        return $this->screenName;
    }
}

使用 $ this-> 运算符是指调用模型拥有的对象,在本例中为Student。

$this用于调用属于拥有模型(类)或引用变量的方法。

self类似,但self用于静态方法和成员。 $ this 用于实例化对象。