PHP面向对象中的重要知识点
Posted 脚本叔叔
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP面向对象中的重要知识点相关的知识,希望对你有一定的参考价值。
转自:http://www.cnblogs.com/stephen-liu74/p/3497440.html
1. __construct:
内置构造函数,在对象被创建时自动调用。见如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php
class
ConstructTest
private
$arg1
;
private
$arg2
;
public
function
__construct(
$arg1
,
$arg2
)
$this
->arg1 =
$arg1
;
$this
->arg2 =
$arg2
;
print
"__construct is called...\\n"
;
public
function
printAttributes()
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
2. parent:
用于在子类中直接调用父类中的方法,功能等同于Java中的super。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?php
class
BaseClass
protected
$arg1
;
protected
$arg2
;
function
__construct(
$arg1
,
$arg2
)
$this
->arg1 =
$arg1
;
$this
->arg2 =
$arg2
;
print
"__construct is called...\\n"
;
function
getAttributes()
return
'$arg1 = '
.
$this
->arg1.
' $arg2 = '
.
$this
->arg2;
class
SubClass
extends
BaseClass
protected
$arg3
;
function
__construct(
$baseArg1
,
$baseArg2
,
$subArg3
)
parent::__construct(
$baseArg1
,
$baseArg2
);
$this
->arg3 =
$subArg3
;
function
getAttributes()
return
parent::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
3. self:
PHP面向对象中的重要知识点