时间:2021-07-01 10:21:17 帮助过:19人阅读
classA{publicfunctionA(){echo'A is constructing...';
}
}
classB{publicfunction__construct(){echo'B is contructing...';
}
}
$a = new A(); // A is constructing...$b = new B(); // B is constructing...
此外,在继承时,应该注意的是:
【子类可以不写构造函数,那么使用父类的构造函数】
classA{protected$name;
publicfunctionA(){echo'A is constructing...
';
}
publicfunctionset_name($name){$this->name = $name;
}
publicfunctionget_name(){return$this->name;
}
}
classBextendsA{/*
public function __construct(){
echo 'B is contructing...
';
}
*/ }
//$a = new A();$b = new B(); // A is constructing...$b->set_name('zhangsan');
echo$b->get_name();
【子类如果写了构造函数,那么不会再调用父类的构造函数了】
classA{protected$name;
publicfunctionA(){echo'A is constructing...
';
}
publicfunctionset_name($name){$this->name = $name;
}
publicfunctionget_name(){return$this->name;
}
}
classBextendsA{publicfunction__construct(){echo'B is contructing...
';
}
}
//$a = new A();$b = new B(); // just echo 'B is contructing...'$b->set_name('zhangsan');
echo$b->get_name(); // zhangsan
【父类的构造函数如果是私有的,可以被继承,但是子类必须有自己的构造函数,并且明确写出来】
classA{protected$name;
privatefunctionA(){echo'A is constructing...
';
}
publicfunctionset_name($name){$this->name = $name;
}
publicfunctionget_name(){return$this->name;
}
}
classBextendsA{publicfunction__construct(){echo'B is contructing...
';
}
}
//$a = new A();$b = new B(); // B is contructing...$b->set_name('zhangsan');
echo$b->get_name(); // zhangsan
版权声明:本文为博主原创文章,未经博主允许不得转载。
以上就介绍了PHP面向对象构造函数说明,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。