php面向对象之-函数重写与函数重载

header("Content-type: text/html; charset=utf-8");
class animal
{
   public $head;
   public function move()
   {
       echo '<br>我是move方法的执行结果!<br>';  
   }
}
class person extends animal
{  
     function move($x)
	 {
	 	 //parent::move();如果调用父类的函数,可以这样调用的。
	     echo '这是子类的移动方法';
	 }	 

 	 //上面子类定义了一个和父类函数名相同的函数,这样叫做函数的重写,子类重写父类的函数,参数可以和父类不一样的,只要子类重写了父类的函数,那么$this->move('2');
//,此时直接调用子类的函数,父类的函数就没有调用。 function __call($name,$args) { if($name=='filter') { $sql=$args[0]; $count=count($args); for($i=1;$i<$count;$i++) { $pattern = "/\?/"; $sql=preg_replace($pattern,str::quote($args[$i]),$sql,1); } return $sql; } else { echo '此函数没有定义',exit; } } }
//上面的代码为函数的重载,当对象访问一个不存在的方法时会调用__call($method_name,$args)函数,其中$method_name为函数的名称,$args为函数的参数;
//如果要定义一个函数,有不确定的参数时可以用上面的函数重载的方法; class str { public static function quote($value) { if (is_int($value)||is_numeric($value)) { return $value; } elseif (is_float($value)) { return sprintf('%F', $value); } trim($value); if(get_magic_quotes_gpc() || get_magic_quotes_runtime()) { return "'" . addcslashes($value, "\n\r\\032") . "'"; } else { return "'" . addcslashes($value, "\000\n\r\\'\"\032") . "'"; } } }
$type=$_GET["type"];
$title=$_GET["title"];
$sql=$per->filter('select * from jilupian where title like ? and type=? limit 10','%'.$title.'%',$type);//此为过滤时写的sql语句
//此为函数重载方法的一个实例

 下面的代码演示了php中不在类中的函数重载(不确定参数,函数名确定);

function x()
{
    $num=func_num_args();
	$args=func_get_args();
	if($num)
	{
		for($i=0;$i<$num;$i++)
		{
			print_r($args[$i]);
			echo '<br />';
		}
	}	
}
$arr=array(
'sdfdf',
'1243',
'sdf34234'
);
x('asdf','sdfsdf','123',4324,$arr);

 

posted @ 2013-03-14 16:03  qingq  阅读(524)  评论(0编辑  收藏  举报