php经过魔术方法_call实现类函数重载

WBOY
Release: 2016-06-13 11:59:07
Original
835 people have browsed it

php通过魔术方法__call实现类函数重载

        由于在php是弱类型语言,并不像c++一样可以通过改变函数返回值的类型和函数的参数个数进行重载!但在实际开发中可能会有重载函数的需求,为了满足开发需求,我们可以通过魔术方法__call()来实现函数重载

class Templates { <span style="white-space:pre">	</span>function __call($fun,$argv){    	<span style="white-space:pre">	</span>if($fun=="assign"){    		<span style="white-space:pre">	</span>if(count($argv)==1){    			<span style="white-space:pre">	</span>$this->assign1($argv[0]);    		<span style="white-space:pre">	</span>}    		elseif(count($argv)==2){    			$this->assign2($argv[0],$argv[1]);    		}    	}    } //assign函数接受参数  function assign2($key,$value){  			if(isset($key)&&!empty($value)){  				$this->val["$key"]=$value;  			}else{  				exit("ERROR:请设置变量");  			}  }  //重载assign函数接受数组  function assign1($array){  			if(!empty($array)){  				foreach($array as $key => $value){  					$this->val["$key"]=$value;  				}  			}else{  				exit("ERROR:请设置数组");  			}  }}
Copy after login

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!