Ismail
Ismail

Reputation: 9612

php object variable as classname

when I want to statically access the class JSON using an variable it is possible.

Code:

<?php
$classname = "JSON";
$classname::echo_output();
?>

But when I want to use an object variable to statically access the class it fails. code:

<?php
class someclass{
public $classname = "JSON";
    public function __construct(){
        $this->classname::echo_output();
    }
}
?>

Try it yourself.

How I solved it was $classname = $this->classname; But is there any other possible way to solve this?

Upvotes: 0

Views: 278

Answers (4)

Ismail
Ismail

Reputation: 9612

By some research and javascript knowledge this solution would be the simpliest.

<?php
class someclass{
public $classname = "JSON";
    public function __construct(){
        $that = (array) $this;
        $that["classname"]::echo_output();
    }
}
?>

Just cast objects to arrays.

This way you don't have to define a variable for each dynamic classname.

Upvotes: 0

inf3rno
inf3rno

Reputation: 26157

By PHP 5.4+ you can do this with ReflectionClass in a single line.

(new \ReflectionClass($this->classname))->getMethod('echo_output')->invoke(null);

under PHP 5.4

call_user_func(array($this->classname, 'echo_output'));

but I don't recommend this.

Instead of using static methods, you should create instances, inject them, and call their methods...

interface Helper{
    public function echo_output();
}

class JSONHelper implements Helper {
    ...
}

class someclass{
    public function __construct(Helper $helper){
        $helper->echo_output();
    }
}

new someclass(new JSONHelper()); //multiple instances
new someclass(JSONHelper::getInstance()); //singleton
new someclass($helperFactory->createHelper()); //factory
new someclass($container->getHelper()); //IoC container

Upvotes: 0

Oscar M.
Oscar M.

Reputation: 1086

If echo_output actually exists in the class your calling, this should work but you have to assign the property to a variable first.

public function __construct(){
    $classname = $this->classname;
    $classname::echo_output();
}

Upvotes: 0

Mikk
Mikk

Reputation: 2229

You can use call_user_func function in order to achieve this

<?php

class someclass{

public $classname = "JSON";

    public function __construct(){
        call_user_func([$this->classname, 'echo_output']);
    }

}
?>

Upvotes: 2

Related Questions