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

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

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

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

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

)

Copy after login

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

修改后的程序如下:

class test{
private $parameter;
public function __construct($parameter){
$this->parameter=$parameter;
echo "test类构造方法被调用
";
}
public function getParameter(){
echo $this->parameter; // 修改这里
}
}
class test1{
private static $test=null;
public function __construct(){
self::$test = new test("test"); // 修改这里
echo "test1类构造方法被调用
";
}
public static function show(){
echo "show()方法被调用";
self::$test->getParameter();//
}
}
$test1 = new test1();
test1::show();
?>
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!