PHP动态类加载 [英] PHP dynamic class loading

查看:115
本文介绍了PHP动态类加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组,我要转换为一个值对象。

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

我的值对象类如下:

/* file UserVO.php*/
 class UserVO
 {
    public $id;
    public $email;

     public function __construct($data)
     {
         $this->id = (int)$data['id'];
         $this->email = $data['email'];
     } 
 }

我创建了一个值对象数组,

And I create my array of value objects as follows:

/* file UserService.php*/
$array = array(
array(...),
array(...));
$count = count($array);
for ($i = 0; $i < $count; $i++)
{
   $result[] = new UserVO($array[$i]);
}
return $result;

确定,所以这一切都正常。但是,我想详细说明要动态创建的VO,这样我就可以有一个动态函数来创建我的VO。

OK, so this all works fine. However, I'd like to specificy the VO that is to be created dynamically, so that I can have a single dynamic function to create my VO's.

像: / p>

Something like:

$ret = create_vo($array, 'UserVO');

function create_vo($data, $vo)
{
  $count = count($data);
  for ($i = 0; $i < $count; $i++)
  {
     $result[] = new $vo($data[$i]); //this obviously wont work...Class name must be a valid object or a string
  }
  return $result;
}

我意识到我可以通过switch语句VO的)...但毫无疑问,一个更优雅的解决方案。如果我可以根据需要延迟加载VO,而不是多个包括

I realise that I could do this with a switch statement (iterating through all my VO's)...but there is no doubt a much much more elegant solution. It would also be supercool if I could lazy load the VO's as needed, instead of having multiple 'includes'

任何帮助非常感激。

推荐答案

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

试过了?它的工作原理正如预期的(在php 5.1,我不知道它是如何与OOP在PHP 4,但如果你使用 __构造的构造函数,这应该工作)。

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).

为避免多次使用,请在使用任何类之前定义魔术函数 __ autoload

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

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

所以先调用 new UserVo 将触发此函数包含文件 myclasses / UserVo.php

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

这篇关于PHP动态类加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆