Maison  >  Article  >  développement back-end  >  php经过魔术方法_call实现类函数重载

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

WBOY
WBOYoriginal
2016-06-13 11:59:07829parcourir

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:请设置数组");  			}  }}

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn