第 9 章 使用对象

第 9 章 使用对象

9.1 创建一个对象

";

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 对象的属性

color $car->make $car->model
"; // 改变对象的属性 $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 对象方法

具有方法的一个类

sayHello();
?>

结果:

HELLO!

在一个方法中访问类属性

name.";
    }
}

$object1 = new myClass();
$object1->sayHello();
?>

结果:

HELLO! My name is Jimbo.

在一个方法中改变一个属性的值

name = $name;
    }
    function sayHello() {
        echo "HELLO! My name is $this->name.";
    }
}

$object1 = new myClass();
$object1->sayHello();
echo "
"; $object1->setName("Julie"); $object1->sayHello(); ?>

结果

HELLO! My name is Jimbo.
HELLO! My name is Julie.

9.2 对象继承

继承其父类的一个类

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.

子类的方法覆盖了父类的方法

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.

你可能感兴趣的:(第 9 章 使用对象)