新手请教下,类属性能初始化为一个其他类的实例对象吗

WBOY
Release: 2016-06-13 12:02:13
Original
1103 people have browsed it

新手请问下,类属性能初始化为一个其他类的实例对象吗
如果行的话,那语法是什么样的?

------解决方案--------------------

class A {}<br />class B {<br />  public $o;<br />  function __construct() {<br />    $this->o = new A;<br />  }<br />}<br />$p = new B;<br />print_r($p);
Copy after login
B Object<br />(<br />    [o] => A Object<br />        (<br />        )<br /><br />)<br /><br />
Copy after login

------解决方案--------------------
引用:
@xuzuning版主
<?php<br />	class test{<br />		private $parameter;<br />		public function __construct($parameter){<br />			$this->parameter=$parameter;<br />			echo "test类构造方法被调用<br/>";<br />		}<br />		public function getParameter(){<br />			echo $parameter;<br />		}<br />	}<br />	class test1{<br />		private static $test=null;<br />		public function __construct(){<br />			$test = new test("test");<br />			echo "test1类构造方法被调用<br/>";<br />		}<br />		public static function show(){<br />			echo "show()方法被调用";<br />			self::$test->getParameter();//<br />		}<br />	}<br />	$test1 = new test1();<br />	test1::show();<br />?>
Copy after login

以上代码这句:self::$test->getParameter();会报Fatal error: Call to a member function getParameter() on a non-object,我把test1类的属性$test改为普通属性,show()方法改为普通方法,还是报同样的错误,为什么?


你的程序写错了。
1.第9行,你要显示$parameter属性,应是 echo $this->parameter; 而不是echo $parameter;
2.第15行 $test = new test("test"); 这个赋值并不会赋值到 private static $test,所以第20行的self::$test 是等于null
因此15行需要改为 self::$test = new test("test");

修改后的程序如下:
<br /><?php<br />    class test{<br />        private $parameter;<br />        public function __construct($parameter){<br />            $this->parameter=$parameter;<br />            echo "test类构造方法被调用<br/>";<br />        }<br />        public function getParameter(){<br />            echo $this->parameter; // 修改这里<br />        }<br />    }<br />    class test1{<br />        private static $test=null;<br />        public function __construct(){<br />            self::$test = new test("test");  // 修改这里<br />            echo "test1类构造方法被调用<br/>";<br />        }<br />        public static function show(){<br />            echo "show()方法被调用";<br />            self::$test->getParameter();//<br />        }<br />    }<br />    $test1 = new test1();<br />    test1::show();<br />?><br />
Copy after login


test类构造方法被调用
test1类构造方法被调用
show()方法被调用test

最后不得不说,自己有问题应该开贴,不应该在别人贴里面问。

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!