Home > Backend Development > PHP Tutorial > php中$this->含义分析_PHP

php中$this->含义分析_PHP

WBOY
Release: 2016-06-01 12:22:26
Original
837 people have browsed it

我们一般是先声明一个类,然后用这个类去实例化对象!
但是,当我们在声明这个类的时候,想在类本身内部使用本类的属性或者方法。应该怎么表示呢?
例如:
我声明一个User类!它只含有一个属性 $name;
class User
{
public $_name;
}
现在,我给User类加个方法。就用getName()方法,输出$name属性的值吧! 复制PHP内容到剪贴板
PHP代码:
复制代码 代码如下:
class User
{
public $name;
function getName()
{
echo $this->name;
}
}
//如何使用呢?
$user1 = new User();
$user1->name = '张三';
$user1->getName(); //这里就会输出张三!
$user2 = new User();
$user2->name = '李四';
$user2->getName(); //这里会输出李四!

怎么理解呢?
我上面创建了两个User对象。分别是 $user1 和 $user2 。
当我调用 $user1->getName()的时候。 上面User类中的代码 echo $this->name ; 就是相当于是 echo $user1->name;
大概就是这么个意思!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template