我总是看到PHP中的变量$this
,我不知道它用于什么。我从来没有亲自使用它,搜索引擎忽略$
,我最终搜索单词“this”。
有人能告诉我变量$这是如何在PHP中工作?
我总是看到PHP中的变量$this
,我不知道它用于什么。我从来没有亲自使用它,搜索引擎忽略$
,我最终搜索单词“this”。
有人能告诉我变量$这是如何在PHP中工作?
它是对当前对象的引用,它在面向对象代码中最常用。
实施例:
<?php
class Person {
public $name;
function __construct($name) {
$this->name = $name;
}
};
$jack = new Person('Jack');
echo $jack->name;
此存储“杰克字符串作为创建的对象的属性。
这是从本身内引用类的实例的方式,与许多其他面向对象的语言一样。
从PHP docs:
伪变量$这是可用的时 的方法是从 对象上下文中调用。 $这是调用对象(通常是该方法所属的对象 , ,但如果从辅助对象的 上下文中静态调用 方法,可能还有另一个对象)的引用 。
它指的是当前类的实例,因为计算器表示。
查看PHP Docs。这是在第一个例子下解释的。
当你创建一个你有(在许多情况下)实例变量和方法(又名。函数)的类。 $ 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
了解在PHP中$this
变量的最好方法是问问PHP是什么。不要问我们,问的编译器:
print gettype($this); //object
print get_object_vars($this); //Array
print is_array($this); //false
print is_object($this); //true
print_r($this); //dump of the objects inside it
print count($this); //true
print get_class($this); //YourProject\YourFile\YourClass
print isset($this); //true
print get_parent_class($this); //YourBundle\YourStuff\YourParentClass
print gettype($this->container); //object
您忘记了几个分号:D – smileBeda 2015-05-21 23:25:02
我知道它的老问题,反正约$这个另一个确切的解释。 $ this主要用于引用类的属性。
实施例:
Class A
{
public $myname; //this is a member variable of this class
function callme() {
$myname = 'function variable';
$this->myname = 'Member variable';
echo $myname; //prints function variable
echo $this->myname; //prints member variable
}
}
输出:
function variable
member variable
$this
是a reference to the calling object(通常是该方法所属的对象,但可能的另一种对象,如果该方法是从内静态调用次要对象)。
$这是一个特殊的变量,它指的是同一个对象即。本身。
它实际上是指当前类
这里的实例是将清除上面的语句
<?php
class Books {
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $par;
}
function getPrice(){
echo $this->price ."<br/>";
}
function setTitle($par){
$this->title = $par;
}
function getTitle(){
echo $this->title ." <br/>";
}
}
?>
请详细说明一下 – 2016-04-12 06:47:12
让我们看看,如果我们不使用$这并尽量有实例变量会发生什么情况为例和 构造函数参数具有相同的名称与下面的代码片段
<?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;
?>
此相呼应“汤姆”
您的代码片段是完全一样的,还是我错过了什么? – Demento 2016-06-19 15:40:49
@Demento:是的。我修复了它,在第二个构造函数中使用了'$ this'。 – 2016-06-19 17:01:55
+1的术语“当前对象”,因为它是描述的'$ this'有时非直观的行为更准确的方法。 – 2009-10-06 14:50:24
在KillerPHP OOP教程中看到类似的示例代码:) http://www.killerphp.com/tutorials/php-objects-page-1/ – Edson 2017-01-07 08:59:06