Augusto
Augusto

Reputation: 819

PHP - Treating a class as an object

I need to assign a class (not an object) to a variable. I know this is quite simple in other programming languages, like Java, but I can't find the way to accomplish this in PHP.

This is a snippet of what I'm trying to do:

class Y{

    const MESSAGE = "HELLO";

}

class X{

    public $foo = Y; // <-- I need a reference to Class Y

}

$xInstance = new X();
echo ($xInstance->foo)::MESSAGE; // Of course, this should print HELLO

Upvotes: 0

Views: 114

Answers (3)

Augusto
Augusto

Reputation: 819

I found out that you can treat a reference to a Class just like you would handle any regular String. The following seems to be the simplest way.

Note: In the following snippet I've made some modifications to the one shown in the question, just to make it easier to read.

class Y{
    const MESSAGE="HELLO";

    public static function getMessage(){
        return "WORLD";
    }

}
$var = "Y";
echo $var::MESSAGE;
echo $var::getMessage();

This provides a unified mechanism to access both constants and/or static fields or methods as well.

Upvotes: 0

James C
James C

Reputation: 14169

You could use reflection to find it (see Can I get CONST's defined on a PHP class?) or you could a method like:

<?php

class Y
{
    const MESSAGE = "HELLO";
}

class X
{
    function returnMessage()
    {
        return constant("Y::MESSAGE");
    }
}

$x = new X();
echo $x->returnMessage() . PHP_EOL;

edit - worth also pointing out that you could use overloading to emulate this behaviour and have access to a property or static property handled by a user defined method

Upvotes: 0

zerkms
zerkms

Reputation: 255115

In php you cannot store a reference to a class in a variable. So you store a string with class name and use constant() function

class Y{

    const MESSAGE = "HELLO";

}

class X{

    public $foo = 'Y';

}

$xInstance = new X();
echo constant($xInstance->foo . '::MESSAGE'); 

Upvotes: 3

Related Questions