您好,欢迎访问一九零五行业门户网

php面向对象要点[转]

__constructarg1 = $arg1; $this->arg2 = $arg2; print__construct is called...\n; } publicfunctionprintattributes() {print'$arg1 = '.$this->arg1.' $arg2 = '.$this->arg2.\n; }}$testobject = new constructtest(arg1,arg2); $testobject->printattributes();
运行结果如下:
stephens-air:desktop$ php test.php __construct is called...$arg1 = arg1 $arg2 = arg2
parent用于在子类中直接调用父类中的方法
arg1 = $arg1; $this->arg2 = $arg2; print__construct is called...\n; } functiongetattributes() {return'$arg1 = '.$this->arg1.' $arg2 = '.$this->arg2; }}classsubclassextendsbaseclass {protected$arg3; function__construct($basearg1, $basearg2, $subarg3) {parent::__construct($basearg1, $basearg2); $this->arg3 = $subarg3; } functiongetattributes() {returnparent::getattributes().' $arg3 = '.$this->arg3; }}$testobject = new subclass(arg1,arg2,arg3); print$testobject->getattributes().\n;
运行结果如下:
stephens-air:desktop$ php test.php __construct is called...$arg1 = arg1 $arg2 = arg2 $arg3 = arg3
self
在类内调用该类静态成员和静态方法的前缀修饰,对于非静态成员变量和函数则使用this。printself();
运行结果如下:
stephens-air:desktop$ php test.php this is suba::printself.this is subb::printself.
static关键字不仅仅可以用于实例化。和self和parent一样,static还可以作为静态方法调用的标识符,甚至是从非静态上下文中调用。在该场景下,self仍然表示的是当前方法所在的类。见如下代码:
ownedgroup = static::getgroup(); } publicfunctionprintgroup() {printmy group is .$this->ownedgroup.\n; } publicstaticfunctiongetinstance() {returnnewstatic(); } publicstaticfunctiongetgroup() {returndefault; }}classsubaextendsbase {}classsubbextendsbase {publicstaticfunctiongetgroup() {returnsubb; }}suba::getinstance()->printgroup();subb::getinstance()->printgroup();
运行结果如下:
stephens-air:desktop$ php test.php my groupisdefaultmy groupis subb
__destruct
析构方法的作用和构造方法__construct刚好相反,它只是在对象被垃圾收集器收集之前自动调用,我们可以利用该方法做一些必要的清理工作。innerclass = new innerclass(); } publicfunction__clone() {$this->innerclass = clone$this->innerclass; print__clone is called.\n; }}$outera = new outerclass();printbefore calling to clone.\n;$outerb = clone$outera;printafter calling to clone.\n;$outera->innerclass->id = 20;printin outera: ;$outera->innerclass->printself();printin outerb: ;$outerb->innerclass->printself();
运行结果如下:
stephens-air:desktop$ php test.php before calling to clone.__clone is called.after calling to clone.in outera: $id=20in outerb: $id=10
const
php5可以在类中定义常量属性。和全局常量一样,一旦定义就不能改变。常量属性不需要像普通属性那样以开头,按照惯例,只能用大写字母来命名常量。另外和静态属性一样,只能通过类而不能通过类的实例访问常量属性,引用常量时同样也不需要以 以上就介绍了php面向对象要点[转],包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。
其它类似信息

推荐信息