[How-to] Variable static class properties

phpBB3 and MOD challenges setup by the staff to test and challenge your phpBB3 coding skills.

[How-to] Variable static class properties

Postby Obsidian » 08 Jun 2009, 09:12

Now, this is only theoretical, but as I and erikfrerejean were discussing earlier on IRC in #startrekguide, this is a sloppy way to get the value of a class' property when the class name itself is being provided VIA a variable, without using PHP 5.3 as most hosts will not be running it for some time.

What we're trying to do, you can do in PHP 5.3 using the following code:

Code: Select all
<?php

class someclass
{
    public static $var1 = '';
    public static $var2 = 0;
    public static $var3 = false;
}

class somechild extends someclass
{
    public static $var3 = true;
    public static $var4 = true;
}


$classname = 'someclass';
$varname = 'var3';
$var = $classname::$varname; // Returns false

$classname = 'somechild';
$varname = 'var3';
$var = $classname::$varname; // Returns false
 


Using the following code, this should work in PHP versions prior to PHP 5.3...

Code: Select all
<?php

class someclass
{
    public static $var1 = '';
    public static $var2 = 0;
    public static $var3 = false;
    
    public static function get_static_var
($varname)
    {
        return self::$$varname;
        // As of 5.3, we will want to use LSB for this, to get child classes as well. ;)
        return static::$$varname;
    }
}

class somechild extends someclass
{
    public static $var3 = true;
    public static $var4 = true;
}

//Now, we want to get a var from someclass, do we?

$classname = 'someclass';
$varname = 'var3';
$var = call_user_func(array($classname, '::get_static_var'), $var_name);  // returns FALSE.

// Attempting to get somechild::$var3 should result in false, due to static being used.
// If we had LSB, it would work, however.
$classname = 'somechild';
$varname = 'var3';
$var = call_user_func(array($classname, '::get_static_var'), $var_name);  // returns FALSE.

// And...let's see here...this should return true, I think.
$classname = 'somechild';
$varname = 'var4';
$var = call_user_func(array($classname, '::get_static_var'), $var_name);  // returns TRUE.


// See example three of http://php.net/manual/en/function.call-user-func.php for more detailed example.
?>
うるさいうるさいうるさい!

StopForumSpam Spam Reporting Database
Giving xrumer and friends a great big "screw you" since 2007.
User avatar
Obsidian    
Supporter
Supporter
 
Posts: 2250
Joined: 04 Mar 2008, 23:35
Gender: Male
phpBB Knowledge: 10


Return to phpBB3 Challenges at phpBB Academy

Who is online

Users browsing this forum: No registered users and 1 guest