http://bbs.17php.com/show_title.php?id=1443

解决方案 »

  1.   

    如果连重载都没有哪还有脸说OO<?php//基类
    class Animal
    {
         //基类的属性
         public $name; //名字     //基类的构造函数
         public function __construct( $name )
         {
              $this->name = $name;
         }
    }//派生类
    class Person extends Animal //Person类继承了Animal类
    {
         public $personSex; //性别
         public $personAge; //年龄     //继承类的构造函数
         function __construct( $personSex, $personAge )
         {
              parent::__construct( "heiyeluren" ); //使用parent调用了父类的构造函数
              $this->personSex = $personSex;
              $this->personAge = $personAge;
         }     function printPerson()
         {
              print( $this->name. " is " .$this->personSex. ",this year " .$this->personAge );
          }
    }//实例化Person对象
    $personObject = new Person( "male", "");//执行打印
    $personObject->printPerson(); //输出:heiyeluren is male,this year ?> 
      

  2.   

    php可以用模拟重载,比如使用call,在调用不存的方法时执行,比如class a{
    function __call($methodName,$methodArgs){
    $newMethodName=$methodName.count($methodArgs);//这时候可以用参数个数/类型等判断
    if (method_exists($this,$newMethodName)){
    call_user_func_array(array($this,$newMethodName),$methodArgs);
    }
    }function x1($arg1){echo $arg1;}//实际上执行另外两个不同名的方法,来模拟
    function x2($arg1,$arg2){echo $arg1.$arg2;}
    }
    $a=new a;
    $a->x(1);//本来是不可能的,但是call的时候判断了,call内容要自己写
    $a->x(1,2);
    call在实例化后调用,构造函数就不行了,那就修改构造函数class b{
    function __construct(){
    $newMethodName=__CLASS__.func_num_args();//这时候可以用参数个数/类型等判断
    $newMethodArgs=func_get_args();
    if (method_exists($this,$newMethodName)){
    call_user_func_array(array($this,$newMethodName),$newMethodArgs);
    }
    }function b1($arg1){echo $arg1;}//实际上执行另外两个不同名的方法,来模拟
    function b2($arg1,$arg2){echo $arg1.$arg2;}
    }$b=new b(1);
    $b=new b(1,2);