实例化php类的时候如何传参

       当我们实例化一个php类的时候,要怎么传递参数呢?这取决于该类的构造方法。
例:
person.class.php

<?php	
	class person{
		var $name;
		var $color;
		var $sex;
		var $age;
		function __construct($name,$age='',$sex='boy'){
			$this->name = $name;			
			$this->age = $age;			
			$this->sex = $sex;			
			$this->color = 'yello';		
		}		
		function eat(){			
			echo $this->name.'要吃饭';		
		}		
		function xinxi(){			
			echo $this->name.' is '.$this->sex.' and age is '.$this->age.' fuse is '.$this->color;		
		}		
		function zuoyong(){		    
			//类似于这样的内部调用,相当于把eat()的代码引入到zuoyong()里面,而不是跳转到eat()里面继续执行			
			//如果是http://localhost/zuoyong?food=xigua这样的url来调用zuoyong()			
			//那么eat()中可直接通过$_GET['food']获取url参数,因为全局变量可在函数内部使用			
			$this->eat();		
		}			
	}
?>

son.php

<?php	

	include('person.class.php');	
	
	$son = new person('cuihua',25,'girl');
	
	//此处的参数传递要和类的构造方法里面的参数顺序对应	
	//$son->xinxi();
	//cuihua is girl and age is 25 fuse is yello	
	
	$son->name = '田妞';	
	
	$son->eat();//田妞要吃饭
?>

       注:php类的属性($name$age等)可以在该类的全局范围内使用,可以把类的属性视为“该类的”全局变量。但是当外部程序重新调用这个类中的方法时,该类会重新被实例化,也就是说要再次执行构造方法,那么上一次给$name等属性赋的值就会被清空,所以$name等属性的值不会像常量或是session中的值那样一直保持下去。

son2.php

<?php	

	include('person.class.php');	

	$son = new person('cuihua',25,'girl');	

	$son2 = $son;	

	$son2->name = '田妞';	

	$son->eat();//田妞要吃饭

?>

       当我把$son对象赋予$sin2之后,改变了$son2的name参数,此时发现$son的name参数也响应的跟着改变,由此可见:在php5中,把对象赋值给变量,是按引用传递对象,而不是进行值传递,此时并不会创建$son的副本。传递对象到函数,或从方法返回对象,是引用传递还是值传递,待验证。


       可以通过var_dump()打印对象,不过只能打印对象的属性,它的方法不能打印出来,要想获取对象的方法列表,可以用get_class_methods函数。

<?php

	$son = new person('cuihua',25,'girl');
	var_dump($son);

	/*object(person)[1]  
	public 'name' => string 'cuihua' (length=6)  
	public 'color' => string 'yello' (length=5)  
	public 'sex' => string 'girl' (length=4)  
	public 'age' => int 25*/ 

	$mon = get_class_methods($son);
	var_dump($mon);

	/*array (size=4)  
	0 => string '__construct' (length=11)  
	1 => string 'eat' (length=3)  
	2 => string 'xinxi' (length=5)  
	3 => string 'zuoyong' (length=7)*/
?>

文章转载自:这篇博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值