本文实例讲述了PHP面向对象程序设计之对象生成方法。,具体如下:
对象
看个例子
<?php
abstract class Employee { // 雇员
protected $name;
function __construct( $name ) {
$this->name = $name;
}
abstract function fire();
}
class Minion extends Employee { // 奴隶 继承 雇员
function fire() {
print "{$this->name}: I'll clear my deskn";
}
}
class NastyBoss { // 坏老板
private $employees = array();
function addEmployee( $employeeName ) { // 添加员工
$this->employees[] = new Minion( $employeeName ); // 代码灵活性受到限制
}
function projectFails() {
if ( count( $this->employees ) > 0 ) {
$emp = array_pop( $this->employees );
$emp->fire(); // 炒鱿鱼
}
}
}
$boss = new NastyBoss();
$boss->addEmployee( "harry" );
$boss->addEmployee( "bob" );
$boss->addEmployee( "mary" );
$boss->projectFails();
// output:
// mary: I'll clear my desk
?>
再看一个更具有灵活性的案例
<?php
abstract class Employee {
protected $name;
function __construct( $name ) {
$this->name = $name;
}
abstract function fire();
}
class Minion extends Employee {
function fire() {
print "{$this->name}: I'll clear my deskn";
}
}
class NastyBoss {
private $employees = array();
function addEmployee( Employee $employee ) { // 传入对象
$this->employees[] = $employee;
}
function projectFails() {
if ( count( $this->employees ) ) {
$emp = array_pop( $this->employees );
$emp->fire();
}
}
}
// new Employee class...
class CluedUp extends Employee {
function fire() {
print "{$this->name}: I'll call my lawyern";
}
}
$boss = new NastyBoss();
$boss->addEmployee( new Minion( "harry" ) ); // 直接以对象作为参数,更具有灵活性
$boss->addEmployee( new CluedUp( "bob" ) );
$boss->addEmployee( new Minion( "mary" ) );
$boss->projectFails();
$boss->projectFails();
$boss->projectFails();
// output:
// mary: I'll clear my desk
// bob: I'll call my lawyer
// harry: I'll clear my desk
?>
单例
<?php
class Preferences {
private $props = array();
private static $instance; // 私有的,静态属性
private function __construct() { } // 无法实例化,私有的构造函数
public static function getInstance() { // 返回对象 静态方法才可以被类访问,静态方法中要有静态属性
if ( empty( self::$instance ) ) {
self::$instance = new Preferences();
}
return self::$instance;
}
public function setProperty( $key, $val ) {
$this->props[$key] = $val;
}
public function getProperty( $key ) {
return $this->props[$key];
}
}
$pref = Preferences::getInstance();
$pref->setProperty( "name", "matt" );
unset( $pref ); // remove the reference
$pref2 = Preferences::getInstance();
print $pref2->getProperty( "name" ) ."n"; // demonstrate value is not lost
?>







