PHP namespace & constructor issues

后端 未结 2 614
挽巷
挽巷 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:43

    From php manual:

    For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, and the class did not inherit one from a parent class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.

    As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.

    You can use the name of the class as constructor (unless the class is namespaced) because PHP5 keeps this for backwards compatibility with PHP4, but this is not recomended because it is the old way and may be removed in newer versions of php. So unless you are writting something that needs for some reason to be PHP4 compatible use __construct().

    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题