doukezi4576 2014-08-06 22:29
浏览 289
已采纳

在PHP中调用不同的命名空间或类

on index.php I have below code

require 'Bootstrap.php';
require 'Variables.php';

function __autoload($class){
    $class = str_replace('Control\\', '', $class);
    require_once 'class/'.$class.'.php';
}

$bootstratp = new Control\Bootstrap();

on Bootstrap.php

namespace Control;
class Bootstrap{
  function __construct(){
    Constructor::load_html();
    self::same_namespace_different_class();
  }
  static function same_namespace_different_class(){
    Variables::get_values();
  }
}

in class/Constructor.php

class Constructor{
  static function load_html(){
    echo 'html_loaded';
  }
  static function load_variables(){
     echo 'load variables';
  }
}

and on Variables.php

namespace Control;
class Variables{
    static function get_values(){
        Constructor::load_variables();
    }
}

Assume, In total I have 4 PHP files including 3 Class files of 2 different namespaces. I also have a __autoload function on index.php that will call classes from 'class' folder but my 'Control' namespace files are in root folder.

When I echo the class name in __autoload i get the all the class names starting with 'Control\' even when I am calling a class from global namespace.

I am getting below error

Warning: require_once(class/Variables.php): failed to open stream: No such file or directory in _____________ on line 10

what is wrong with my code??

展开全部

  • 写回答

1条回答 默认 最新

  • doufei2007 2014-08-06 22:34
    关注

    When I echo the class name in __autoload i get the all the class names starting with 'Control\' even when I am calling a class from global namespace.

    This is because in Bootstrap.php all the code is in Control namespace (namespace Control). So when you use:

    Variables::get_values();
    

    you call

    \Control\Variables::get_values();
    

    if you want to use Variables from global namespace you should use here:

    \Variables::get_values();
    

    Of course, the same happens for in Variables.php file:

    Constructor::load_variables();
    

    As Constructor is defined in global namespace (in class/Constructor.php there is no namespace used), you should access it here using:

    \Constructor::load_variables();
    

    If it's still unclear you could also look at this question about namespaces in PHP.

    You should also notice that using __autoload is not recommended. You should use spl_autoload_register() now. Documentation about autoloading

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?