PHP namespace & constructor issues

后端 未结 2 615
挽巷
挽巷 2021-01-23 03:19

I am trying the following :

//file1.
namespace foo;
class mine {
     public function mine() {
         echo \"Does not work!!\";
     } 
}
//file2. 

use foo/mi         


        
2条回答
  •  孤街浪徒
    2021-01-23 03:50

    Below are 2 different possible solutions to the namespace\constructor problem

    //parentclass.php
    class parentclass
    {
      public function __construct()
      {
        //by default, strip the namespace from class name
        //then attempt to call the constructor
        call_user_func_array([$this,end(explode("\\",get_class($this)))],func_get_args());
      }
    }
    
    //foo/bar.php
    namespace foo;
    class bar extends \parentclass
    {
      public function bar($qaz,$wsx)
      {
      //...
      }
    }
    
    $abc = new foo\bar(1,2);
    

    and

    //parentclass.php
    class parentclass
    {
      public function __construct()
      {
        //by default, replace the namespace separator (\) with an underscore (_)
        //then attempt to call the constructor
        call_user_func_array([$this,preg_replace("/\\/","_",get_class($this))],func_get_args());
      }
    }
    
    //foo/bar.php
    namespace foo;
    class bar extends \parentclass
    {
      public function foo_bar($qaz,$wsx)
      {
      //...
      }
    }
    
    $abc = new foo\bar(1,2);
    

提交回复
热议问题