med*_*iev 122
它是对当前对象的引用,它最常用于面向对象的代码中.
例:
<?php
class Person {
public $name;
function __construct( $name ) {
$this->name = $name;
}
};
$jack = new Person('Jack');
echo $jack->name;
Run Code Online (Sandbox Code Playgroud)
这将'Jack'字符串存储为创建的对象的属性.
Eri*_*ski 37
$this在php中了解变量的最佳方法是询问PHP是什么.不要问我们,请问编译器:
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 ->
Run Code Online (Sandbox Code Playgroud)
loy*_*ola 14
我知道它的老问题,无论如何另一个关于$ this的确切解释.$ 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
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
function variable
member variable
Run Code Online (Sandbox Code Playgroud)
小智 7
让我们看看如果我们不使用$ this会发生什么,并尝试使用以下代码片段具有相同名称的实例变量和构造函数参数
<?php
class Student {
public $name;
function __construct( $name ) {
$name = $name;
}
};
$tom = new Student('Tom');
echo $tom->name;
?>
Run Code Online (Sandbox Code Playgroud)
它没有回音
<?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;
?>
Run Code Online (Sandbox Code Playgroud)
这与'汤姆'相呼应
| 归档时间: |
|
| 查看次数: |
179544 次 |
| 最近记录: |