第 9 章 使用对象
2017-10-18 本文已影响0人
南北东西总相随
第 9 章 使用对象
9.1 创建一个对象
<?php
class myClass {
//
}
$object1 = new myClass();
echo "\$object1 is an ".gettype($object1).".<br/>";
if (is_object($object1)) {
echo "Really! I swear \$object1 is an object!";
}
?>
结果:
$object1 is an object.
Really! I swear $object1 is an object!
9.1.1 对象的属性
<?php
class myCar {
public $color = "silver";
public $make = "Mazda";
public $model = "Protege5";
}
$car = new myCar();
echo "I drive a: $car->color $car->make $car->model<br/>";
// 改变对象的属性
$car->color = "red";
$car->make = "Porsche";
$car->model = "Boxter";
echo "I drive a: $car->color $car->make $car->model";
?>
结果:
I drive a: silver Mazda Protege5
I drive a: red Porsche Boxter
9.1.2 对象方法
具有方法的一个类
<?php
class myClass {
function sayHello() {
echo "HELLO!";
}
}
$object1 = new myClass();
$object1->sayHello();
?>
结果:
HELLO!
在一个方法中访问类属性
<?php
class myClass {
public $name = "Jimbo";
function sayHello() {
echo "HELLO! My name is $this->name.";
}
}
$object1 = new myClass();
$object1->sayHello();
?>
结果:
HELLO! My name is Jimbo.
在一个方法中改变一个属性的值
<?php
class myClass {
public $name = "Jimbo";
function setName($name) {
$this->name = $name;
}
function sayHello() {
echo "HELLO! My name is $this->name.";
}
}
$object1 = new myClass();
$object1->sayHello();
echo "<br/>";
$object1->setName("Julie");
$object1->sayHello();
?>
结果
HELLO! My name is Jimbo.
HELLO! My name is Julie.
9.2 对象继承
继承其父类的一个类
<?php
class myClass {
public $name = "Matt";
function setName($name) {
$this->name = $name;
}
function sayHello() {
echo "HELLO! My name is $this->name.";
}
}
class childClass extends myClass {
//
}
$object1 = new childClass("Baby Matt");
$object1->sayHello();
?>
结果:
HELLO! My name is Baby Matt.
子类的方法覆盖了父类的方法
<?php
class myClass {
public $name = "Matt";
function setName($name) {
$this->name = $name;
}
function sayHello() {
echo "HELLO! My name is $this->name.";
}
}
class childClass extends myClass {
function sayHello() {
echo "I will not tell you my name.";
}
}
$object1 = new childClass("Baby Matt");
$object1->sayHello();
?>
结果:
I will not tell you my name.