Home  >  Article  >  Backend Development  >  成员变量问题

成员变量问题

WBOY
WBOYOriginal
2016-06-23 13:54:21831browse

最近自学php 看到一段代码 
class queryFactory extends base {
  var $link, $count_queries, $total_query_time;

queryFactory 这个类里面 只有$link, $count_queries, $total_query_time这几个变量。
但是queryFactory 里面有个connect方法
    function connect($zf_host, $zf_user, $zf_password, $zf_database, $zf_pconnect = 'false', $zp_real = false) {
    $this->database = $zf_database;
    $this->user = $zf_user;
    $this->host = $zf_host;
    $this->password = $zf_password;
    $this->pConnect = $zf_pconnect;
    $this->real = $zp_real;

这里面出现了 $this->database ,我没有在queryFactory 和queryFactory 的父类里面找到database这个成员的定义。
但在外面的确能访问到database 这个变量。

请问作者为什么不把database像  var $link, $count_queries, $total_query_time这些变量一样定义在一起。这样使用到底有什么好处和意义啊


回复讨论(解决方案)

function connect($zf_host, $zf_user, $zf_password, $zf_database, $zf_pconnect = 'false', $zp_real = false) {    $this->database = $zf_database;    $this->user = $zf_user;    $this->host = $zf_host;    $this->password = $zf_password;    $this->pConnect = $zf_pconnect;    $this->real = $zp_real;

这是 php4 的编程风格
一般的说,显式的声明在类属性列表的属性,是为了表示这些属性一定存在并可被使用

至于在 connect 方法中将传入的参数赋值给类属性是不可取的

这是 php4 的编程风格
一般的说,显式的声明在类属性列表的属性,是为了表示这些属性一定存在并可被使用

至于在 connect 方法中将传入的参数赋值给类属性是不可取的



$this->database 我可以认为database像var $link, $count_queries, $total_query_time;是这个类的属性吗 

按先?明,後使用的原??好,可以?少不少bug。

这是PHP定义变量的一种形式,和直接在方法外定义是一样的,只要执行了这个connect方法,就能取到;
他不和其他变量一起定义,是想用到的时候再定义,这样就避免定义了变量但有可能不用从而占用内存的情况,这是我觉得最合理的地方。

$this->database ? $link $count_queries 一?,都是???的?性。
都可以?外面使用。

$this->database 我可以认为database像var $link, $count_queries, $total_query_time;是这个类的属性吗 


是的,不是像,而是就是这个类的属性
从调用方式看,你只要调用 connect 方法,就必须传递 $zf_database 参数。那么把它作为类属性保存起来的意义何在呢?
传递给 connect 的参数都是一次性参数,用完就不要了,所以并不需要保存。而且在其他地方也不会被用到

这也是PHP的优势吧,变量不用事先声明

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