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

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

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀