Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php access static member by variable class name

Now I am working with yii framework and I'd like to wrote something like this:

protected static $model = "Customer";
...
public function actionIndex() {
    $model::model()->find(...

Now it works:

protected static $model = "Customer";
protected static $model_obj;
...
public function __construct($controller, $id) {
    $this->model_obj = new self::$model;
...
public function actionIndex() {
    $model_obj::model()->find(...

but creating object for access static member is a bad thing. how to avoid it?

getClass takes object as first parameter and it is not suitable for this purpose

google say:

$a = constant($myClassName . "::CONSTANT");
$b = call_user_func(array($myClassName, "static_method"));

it looks like a horrible peace of shit. using this may make many troubles. another solution?

oh! my problem was another:

$controller::$NAME::model() // error

$controller_name = $controller::$NAME
$controller_name::model() // good

thanks

like image 352
puchu Avatar asked Dec 20 '25 22:12

puchu


1 Answers

class foo
{
  public static function bar()
  {
    return 42;
  }
}

// class name as string

$class = 'foo';

var_dump($class::bar()); // 42

// method name as string

$method = 'bar';

var_dump(foo::$method()); // 42

// class AND method names as strings

var_dump($class::$method()); // 42
like image 125
Lepidosteus Avatar answered Dec 22 '25 13:12

Lepidosteus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!