Home  >  Article  >  Backend Development  >  $this->Meaning Analysis in PHP_PHP Tutorial

$this->Meaning Analysis in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:42:15893browse

We usually declare a class first, and then use this class to instantiate objects!
However, when we declare this class, we want to use the properties or methods of this class within the class itself. How should it be expressed?
For example:
I declare a User class! It only contains one attribute $name;
class User
{
public $_name;
}
Now, I add a method to the User class. Just use the getName() method to output the value of the $name attribute! Copy PHP content to clipboard
PHP code:

Copy code The code is as follows:

class User
{
public $name;
function getName()
{
echo $this->name;
}
}
//How to use it?
$user1 = new User();
$user1->name = 'Zhang San';
$user1->getName(); // Zhang San will be output here!
$user2 = new User();
$user2->name = 'John Doe';
$user2->getName(); //John Doe will be output here!

How do you understand it?
I created two User objects above. They are $user1 and $user2 respectively.
When I call $user1->getName(). The code in the User class above echo $this->name ; is equivalent to echo $user1->name;
That’s probably what it means!

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321004.htmlTechArticleWe usually declare a class first, and then use this class to instantiate objects! However, when we declare this class, we want to use the properties or methods of this class within the class itself. Should...
Statement:
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