我在PHP中经常看到变量$this
,我不知道它是用来做什么的。我从来没有亲自使用过它。
谁能告诉我在PHP中变量$this
是如何工作的?
发布于 2013-12-12 02:23:59
学习PHP语言中$this
变量的最好方法是在不同的上下文中尝试使用解释器:
print isset($this); //true, $this exists
print gettype($this); //Object, $this is an object
print is_array($this); //false, $this isn't an array
print get_object_vars($this); //true, $this's variables are an array
print is_object($this); //true, $this is still an object
print get_class($this); //YourProject\YourFile\YourClass
print get_parent_class($this); //YourBundle\YourStuff\YourParentClass
print gettype($this->container); //object
print_r($this); //delicious data dump of $this
print $this->yourvariable //access $this variable with ->
因此,$this
伪变量具有当前对象的方法和属性。这样的东西很有用,因为它允许您访问类中的所有成员变量和成员方法。例如:
Class Dog{
public $my_member_variable; //member variable
function normal_method_inside_Dog() { //member method
//Assign data to member variable from inside the member method
$this->my_member_variable = "whatever";
//Get data from member variable from inside the member method.
print $this->my_member_variable;
}
}
$this
是对解释器为您创建的Object
的引用,其中包含一个变量数组。
如果在普通类的普通方法内调用$this
,$this
将返回该方法所属的对象(类)。
如果上下文没有父对象,则$this
可能是未定义的。
php.net有一个很大的页面,讨论了面向对象编程以及$this
如何根据上下文运行。https://www.php.net/manual/en/language.oop5.basic.php
发布于 2016-06-19 22:59:00
让我们看看如果我们不使用$this并尝试使用以下代码片段使用相同名称的实例变量和构造函数参数,会发生什么情况
<?php
class Student {
public $name;
function __construct( $name ) {
$name = $name;
}
};
$tom = new Student('Tom');
echo $tom->name;
?>
它回响的只有
<?php
class Student {
public $name;
function __construct( $name ) {
$this->name = $name; // Using 'this' to access the student's name
}
};
$tom = new Student('Tom');
echo $tom->name;
?>
这是对“Tom”的回应。
发布于 2009-10-06 14:47:10
当你创建一个类时,你有(在许多情况下)实例变量和方法(也称为。函数)。$this访问这些实例变量,以便您的函数可以获取这些变量,并执行您想要对它们执行的任何操作。
meder例子的另一个版本:
class Person {
protected $name; //can't be accessed from outside the class
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
// this line creates an instance of the class Person setting "Jack" as $name.
// __construct() gets executed when you declare it within the class.
$jack = new Person("Jack");
echo $jack->getName();
Output:
Jack
https://stackoverflow.com/questions/1523479
复制相似问题