php – "Nested" identifier – using the value of one variable in the identifier of another variable. Is this possible?-ThrowExceptions

Exception or error:

Essentially I want to do the following in PHP (or any language for that matter):

class Foo 
    // some hidden attributes 
    private $num1 = 1;
    private $num2 = 2;
    private $num3 = 3;

    // accessor method that returns a different attribute depending on parameter passed 
    public getNum($num)
        return $num{$num};
$foo = new Foo();
// returns 2 (the value of $num2) 

Rather than using an if-else block/ternary operation or having three separate accessor methods, which seems slower and more cumbersome, it would be nice to “fuse” the identifiers together. I appreciate this might be a stupid question but I am a neophyte so please cut me some slack.

Apologies if this is a duplicate (I did a search in advance).

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *