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 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)