Jump to content

Little help in php Magic Methods


criostage
Go to solution Solved by requinix,

Recommended Posts

Hello, i m trying to learn magic method's and i have an small question on something that probably it's extremely easy, but i m not getting there ... Here's the "simple" code i got:

class MyClass{
       protected static $name;
 
        public static function __callStatic($name, $arguments) {
            $methodPrefix = substr($name, 0,3);
            $methodProperty = strtolower(substr($name, 3));
            
            self::$name = 'Allan';
            echo self::$name;
            
            switch( $methodPrefix ) {
                case 'get':
                    return self::$methodProperty;
                    break;
            }
        }

My objective is to remove all the get and set's we you usually use in the code so i m using the __callStatic in order to retrieve or set variables inside the class, for example setName('John'). My question is if i want get the value of the protected static variable called name, usually you would just do return self::name, but let's say i have an more evolved class and i have several protected static variables (like age, genre), so here an small issue comes into my mind, how can i use the the content of the variable $methodProperty to return the proper protected static variable?

 

My attempts resulted in the following error:

Fatal error: Access to undeclared static property: MyClass::$methodProperty

i understand the error but i have no idea how to work it arround...

 

Thanks in advance.

Edited by criostage
Link to comment
Share on other sites

My initial question would be why would you opt for this method instead of just using self::$name? And if you're trying to access them outside of the class why are they protected?

 

I m using this magic method to create an function to avoid creating  diferent set and get functions within this class for each variable example:

class MyClass{
    protected static $name;
    protected static $age;
 
    public static function __callStatic($name, $arguments) {
        $methodPrefix = substr($name, 0,3);
        $methodProperty = strtolower(substr($name, 3));
            
        self::$name = 'Allan';
        self::$age = '20';
        #echo self::$name;

        switch( $methodPrefix ) {
            case 'get':
                return self::${$methodProperty};
                break;
        }
    }
}

echo 'Hello my name is '. MyClass::getName() . ' and i m ' . MyClass::getAge() .' years old';

The output will be "Hello my name is Allan and i m 20 years old", and btw this code have already the code that i got from requinix reply, so it's working.

 

Try variable variables.

return (isset(self::${$methodProperty}) ? self::${$methodProperty} : null);

 

Tyvm that did the trick :-* , would you mind pointing me out the logic behind it?

Edited by criostage
Link to comment
Share on other sites

  • Solution

Tyvm that did the trick :-* , would you mind pointing me out the logic behind it?

PHP has this crazy feature called variable variables. Lets you use a string value to determine the name of a variable. The syntax is basically either adding another $ or, for more complicated situations, ${}. It works in very many places, actually, and even lets you get and set otherwise invalid variables... as long as you can deal with the potential "bugs" of doing so.

 

Given $methodProperty = "name",

self::${$methodProperty} -> self::$name -> "Allan"
Just try not to use it too much: in, like, damn near every possible situation where they would solve a problem, an array is a better solution. Including this situation: it's better to store the values in an array and bypass all this nonsense. Plus, you have a very convenient array of all the data instead of a bunch of variables. Edited by requinix
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.