Home > Backend Development > PHP Tutorial > PHP private 问题《新手求教》

PHP private 问题《新手求教》

WBOY
Release: 2016-06-23 14:22:31
Original
921 people have browsed it

php private

class Pc{
 private $name;

function __construct($pcName){
$this->name=$pcName;
}
}

我想问为什么在方法中访问private的name需要用$this或者self,我直接用$name不行么?我把$this->name改为$name就有问题!不是private修饰的本类内部都可以访问么?求高手给个详细的解答,谢了

回复讨论(解决方案)

这与是否 private 无关
这是一个变量的作用域的问题
如写作
function __construct($pcName){
  $name=$pcName;
}
那么出了 __construct 变量 $name 就不存在了
所以需要
function __construct($pcName){
  $this->name=$pcName;
}
告诉 php name 是属性

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