Home > Backend Development > PHP Tutorial > php面向对象巧妙应用

php面向对象巧妙应用

WBOY
Release: 2016-06-23 13:24:06
Original
1025 people have browsed it

class test {	public $a,$b;	public function __construct($a,$b)	{		$this->a=$a;		$this->b=$b;	}	public function set($var, $val)	{		$this->$var .= $val;		return $this;	}	public function get()	{		echo $this->a.'-'.$this->b;	}}class test2 {	public $obj;	public function __construct($obj)	{		$this->obj=$obj;	}	public function get()	{		$this->obj->get();	}}$a = 'aaaaa';$b = 'bbbbbb';$set = 'set';/// 1、链条式调用方法$test = new test($a, $b);$test2 = new test2($test);$test->$set('a', '111111')->$set('b', '222222'); //通过字符串变量调用(类)方法  ps:php另一巧妙应用 /// 2、分次调用方法$test->$set('a', '111111');$test->$set('b', '222222');unset($test);$test2->get();
Copy after login

虽然test2实例化已传入test,但是test依然可以通过set方法设置参数,然后影响test2。

上述执行程序结果: ( 上面两种都可以得出相同结果 )

aaaaa111111-bbbbbb222222


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