dtqpw68806 2017-04-23 11:17
浏览 93
已采纳

PHP class_alias,var_dump作为该类

I'm working on a library to connect to the Eventbrite API. I've made it generic enough that a lot of the second level business objects are empty classes. Having said that, when I instantiate those objects, I would still like them to register as different classes. I thought class_alias would be the way to go, but it seems that the original class is what is returned when doing a var_dump.

Current:

<?php

namespace Project;

class_alias(
    '\\Project\\Classes\\Aliaser', 
    '\\Project\\Classes\\Attendee',
    true
);

use Project\Classes\Aliaser;
use Project\Classes\Attendee;

$attendee = new Attendee();
var_dump($attendee)
// Aliaser {}

What I'm shooting for:

$attendee = new Attendee();
var_dump($attendee);
// Attendee {}

I would really like to delete the empty classes in favor of the generic one while also having the new dynamically generated class be registered.

Is that possible without a serious performance hit?

Note: Prefer PHP 5.4 or greater, but PHP 7 is also good.

  • 写回答

1条回答 默认 最新

  • duanpoqiu0919 2017-04-23 20:02
    关注

    You can create an instance of a class without puting the code to a file by using eval:

    // define the class if it does not exists
    if (!class_exists (\Eightfold\Eventbrite\Classes\ApiResource\Question::class)) {
        eval ( 'class Question extends \Eightfold\Eventbrite\Classes\ApiResource {} ');
    }
    
    //create instance
    $instance = new \Eightfold\Eventbrite\Classes\ApiResource\Question ();
    

    P.S. If you don't find another solution without eval then you should consider this quote:

    If eval() is the answer, you're almost certainly asking the wrong question. -- Rasmus Lerdorf, BDFL of PHP

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

报告相同问题?