I’m currently facing a problem, I’m writing a code, where I need to use a class inside another class. Currently, I solve the problem this way:
class foo {
private $bar;
function __construct() {
$this->bar = new different_class();
}
}
However, when I need to use more than 1 class, the code gets a bit long and messy. Is there some other way to do this?
My idea would be to make some sort of global class that could be called directly:
class foo{
function hello(){
return "Hello";
}
}
class bar{
function hi(){
return $foo->hello();
}
}
Is that possible?
Thank you very much!
As others have mentioned, you have three options:
staticmethod, which does not require that you instantiate the class.Using the exact example you gave, a
staticmethod will work. However, astaticmethod has real limitations – it can only be used to return constants or otherstaticproperties.Therefore, depending on the complexity of the actual classes involved, it’s very likely
staticmay not be a viable option in many cases.If this is the case, doing exactly what you do in your first example above is the correct option.