PHP dynamic class loading

后端 未结 4 1882
深忆病人
深忆病人 2021-02-05 23:09

Lets say that I have an array that I want to convert to a value object.

My value object class is as follows:

/* file UserVO.php*/
 class UserVO
 {
    pu         


        
4条回答
  •  鱼传尺愫
    2021-02-05 23:34

    $result[] = new $vo($data[$i]); //this obviously wont work...Class name must be a valid object or a string
    

    Have you tried it? It works just as expected (in php 5.1, I don't know how was it with OOP in php 4, but if you are using __construct for constructor this should work).

    To avoid multiple includes define magic function __autoload before using any class

    function __autoload($className)
    {
        require_once 'myclasses/'.$className.'.php';
    }
    

    So first call new UserVo will trigger this function to include file myclasses/UserVo.php.

提交回复
热议问题