doumizhi0809 2011-02-02 01:28
浏览 146
已采纳

如何在PHP中获取类的指针

If I declared a class in a controller and want to use it in a model without passing the class' pointer, how can I redeclare that class without the "Fatal error: Class already declared"? If I use the get_declared_classes() function, I see that the class is declared, but how can I get the pointer to that class so that I can use it in the model?

Basically, how can I use a class that's been declared but with no pointer.

Any help would be greatly appreciated.

Thanks in advance!

EDIT: Maybe the word "pointer" was misused. Here's some code

// Controller...one file
$class = new Class();
$model = $this->load_model('example.php');
$model->dosomething();

// Model...example.php
function dosomething() {
    // I want to access the class here. Is it only possible to do this by
    // passing a $class parameter to the function or can I do it without
    // passing it as a variable?
}
  • 写回答

1条回答 默认 最新

  • donglu5612 2011-02-02 01:43
    关注

    I think you're mixing terminology. There's no concept of a pointer anywhere in PHP. References are similar concepts, but that's another topic.

    What I think you're trying to do, is use a variable to indicate the class in the model. So, you can use a string. So let's say you want to tell the model to use class Foo, you could inject the class name into the model:

    $model = new Model('foo');
    

    Then, inside the constructor:

    public function __construct($class) {
        $this->className = $class;
    }
    

    Then, when you want to use it, just call new:

    $class = $this->className;
    $obj = new $class();
    

    But note that it has nothing to do with object scope. So you could do it anywhere:

    $class = 'Foo';
    $obj = new $class;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应