简体   繁体   中英

Load php class extend by request

I have two classes:

class Init {
     public function test() {
          echo 1;
     }

     public static function loadSecond() {
          // Load the class
     }
}

class Second extends Init {
     public function test2() {
          echo 2;
     }
}

I need to load Second class only by request. For example:

$init = new Init();
$init->test();

$second = $init::loadSecond();
$second->test2();

Replace // Load the class with

return new Second()

You just need to create a new object. (I do not know why you need it to be that way, but this should work for your purpose.

I'm not sure what you need to do. If you mean to include a class whenever you need it automatically :

As Marcin Orlowski mentionned it, what you need is to use the autoloading function of PHP.

Basically it should look like :

function __autoload ($name)
{
    include "/path/to/my/includes/" . $name . "inc.php";
}

If you mean creating an object from another class, you should probably do like

class Init {
     public function test() {
          echo 1;
     }

     public static function loadSecond() {
          return new Second;
     }
}

class Second extends Init {
     public function test2() {
          echo 2;
     }
}

What you need is class autoloading feature implemented. It's basically supported by PHP, so follow the docs: http://php.net/manual/pl/language.oop5.autoload.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM