duanhuizhe6767 2016-09-13 01:26
浏览 25
已采纳

PHP自动加载扩展类

Based on the response from this question I would expect my code to work but for some reason it is not. I have a simple class that extends a class from my library of classes.

_custom.php

$custom = new MyClass();
class MyClass extends MyAbstractClass{

  public function __construct(){
      parent::__construct();
  }

}

Unfortunately I get this fatal error:

Fatal error: Class 'MyClass' not found in ...

But if I remove the extends MyAbstractClass then the error goes away. It seems the issue is that when attempting to extend the class, it does not attempt to load MyAbstactClass which then causes MyClass to not be found at all.

Any thoughts or suggestions on this?

  • 写回答

1条回答 默认 最新

  • douxi2670 2016-09-13 01:53
    关注

    PHP is an interpreted language, meaning that what is known for PHP to define is the code that parsed before a statement.

    class MyClass extends MyAbstractClass{
    
      public function __construct(){
          parent::__construct(); #you are forcing a construct call, it is not required if the parent constructor has no args.
      }
    
    }
    
    $custom = new MyClass();
    

    With classes you can prevent this behavior by using an autoloader, when an object is called and is undefined, it will try to inject and parse the class by your given code.

    You can define the magic function __autoload() but the spl_autoload_register() is preferred as it is more dynamic and not a constant as the __autoload() function is.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?