0

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
Augusto
  • 779
  • 5
  • 18
  • 1
    Why do you need this? Maybe there's a more idiomatic way to accomplish what you want, – troelskn Mar 03 '13 at 22:37
  • I'm coding a small library and I need to access constants and to call static methods on classes given and run-time. The example above was my simplest way to explain my issue. – Augusto Mar 03 '13 at 22:44

3 Answers3

3

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'); 
zerkms
  • 249,484
  • 69
  • 436
  • 539
0

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

Community
  • 1
  • 1
James C
  • 14,047
  • 1
  • 34
  • 43
0

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.

Augusto
  • 779
  • 5
  • 18