开发者

How to get a class's pointer in 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开发者_JAVA技巧 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?
}


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜