PHP中高级OOP的DEMO


PHP5.3
命名空间

<?php
//哎,为何非要用\了
namespace my\name; // see "Defining Namespaces" section
class MyClass {}
function myfunction() {}
const MYCONST = 1;

$a = new MyClass;
$c = new \my\name\MyClass; // see "Global Space" section
$a = strlen('hi'); // see "Using namespaces: fallback to global
// function/constant" section
$d = namespace\MYCONST; // see "namespace operator and __NAMESPACE__
// constant" section$d = __NAMESPACE__ . '\MYCONST';
echo constant($d); // see "Namespaces and dynamic language features" section
?>


方法重载

<?php
class Overloader{
private $properties=array();

function __get($property_name){
if(isset($this->properties[$property_name])){
return ($this->properties[$property_name]);
}else{
return (null);
}
}

function __set($property_name,$value){
$this->properties[$property_name]=$value;
}

function __call($function_name,$args){
switch($function_name){
case "Say":
switch(count($args)){
case 1:
return $this->Say1($args[0]);
case 2:
return $this->Say2($args[0],$args[1]);
case 3:
return $this->Say3($args[0],$args[1],$args[2]);
default :break;
}
default :break;
}
}

function Say1($one){
return "$one <br />";
}

function Say2($one,$two){
return "$one--$two <br />";
}

function Say3($one,$two,$three){
return "$one--$two--$three <br />";
}
}
$o=new Overloader();
//invoke __set()给一个不存在的属性变量赋值,激活__set()
$o->dynaProp="Dynamic Content"; //自动调用__set()方法
//invoke __get()激活__get()
print($o->dynaProp."<br />");//自动调用__get()方法
//invoke __call()激活__call()
@$o->dynaMethod("Leon","Zeev");//自动调用__call()方法
//方法的重载
$test1=$o->Say("test1");
$test2=$o->Say("test1","test2");
$test3=$o->Say("test1","test2","test3");
echo $test1,'<br />',$test2,'<br />',$test3;
?>

多重继承

<?
interface IFOne {
function getName();
}
interface IFTwo {
function getID();
}
//Php 抽象类
abstract class AbsClsOne {
var $name;
function setName($name) {
$this->name = $name;
}
}
abstract class AbsClsTwo {
var $id;
function setID($id) {
$this->id = $id;
}
}
//单继承 多实现
class ExtendsMoreCls extends AbsClsOne implements IFOne, IFTwo {
var $id;
private static $priVar = "private";
function __construct() { //Php5的 构造函数
self::$priVar = "set private";
$this->id = 0;
}
function __destruct() { //释构函数
echo "ExtendsMoreCls destruct";
}
function getName() {
return $this->name;
}
function getID() {
return $this->id;
}
public static function clsStaticFunc() {
echo "static function";
}
}

$emc = new ExtendsMoreCls ( );
$emc->setName ( "kj021320" );
echo $emc->getName ();
echo "<br>";
echo $emc->getID ();
echo "<br>";
ExtendsMoreCls::clsStaticFunc (); //调用静态方法
echo "<br>";
?>
  1. #1 by rates on 三月 29th, 2009

    php的oop倒是真的没有怎么好好写过啊

(will not be published)

  1. No trackbacks yet.