davey
davey

Reputation: 1791

Using a variable as class name

I have the following:

User::model()->exists($someParamsHere);

Is there a way to make the class name 'User' dynamic? So something like this:

$className::model()->exists($someParamsHere);

But that doesn't seem to work.

I also read something about the ReflectionClass, but i'm not really sure how to use it.

I tried this, but off course the model() method is never called this way:

$reflectionMethod  = new ReflectionMethod($className, 'exists');
$reflectionMethod->invoke(null, $someParamsHere);

Upvotes: 0

Views: 110

Answers (2)

Nikolay Krasnov
Nikolay Krasnov

Reputation: 373

In PHP >= 5.3 works fine:

<?php
class Foo {

    static function Bar() {
        return "Bar";
    }

    static function getFoo() {
        return new static();
    }

    function getBar() {
        return static::Bar();
    }
}

$class = "Foo";

print $class::Bar() . "\n";

print $class::getFoo()->Bar() . "\n";

Result:

Bar
Bar

Upvotes: 1

DaSourcerer
DaSourcerer

Reputation: 6606

$className::model() works with PHP 5.3 and above, if I'm not mistaken. A workaround is to use CActiveRecord::model($className). See the documentation for CActiveRecord.model().

Upvotes: 2

Related Questions