Home > Backend Development > PHP Tutorial > php 给类变量赋值问题

php 给类变量赋值问题

WBOY
Release: 2016-06-20 09:37:07
Original
1668 people have browsed it

private $pagebarnum=10;$this->pagebarnum  = $array['page_name'];$this->set('pagebarnum ',$array['page_name']);/**     * 设定类中指定变量名的值,如果改变量不属于这个类,将throw一个exception     * @param unknown $var     * @param unknown $value     */    function set($var,$value){        if(in_array($var, get_object_vars($this))){            $this->$var = $value;        }else{            $this->error(__FUNCTION__,$var." does not belong to PB_Page!");        }    }
Copy after login

$this->pagebarnum  = $array['page_name'];和$this->set('pagebarnum ',$array['page_name']); 赋值有什么区别,明明我已经在类中定义$pagebarnum,我用set去赋值还有这个必要吗?


回复讨论(解决方案)

变量初始化和调整当然有必要,假设你一个页面需要的参数是10,一个页面的参数是5,你是做两个类吗?

变量初始化和调整当然有必要,假设你一个页面需要的参数是10,一个页面的参数是5,你是做两个类吗?


实例化一个类传参进去能实现,但是没搞懂的是直接用$this->pagebarnum  = $array['page_name'];和set方法中先检查变量存不存在有什么区别?pagebarnum  在我创建类的时候已经定义在去检查有什么含义。

$this->pagebarnum  = $array['page_name'];
$this->set('pagebarnum',$array['page_name']);
的区别在于:后者不会对 不存在的属性 pagebarnum 赋值,而前者会对不存在的属性 pagebarnum 创建一个公有的 pagebarnum 属性

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