Shortening variables etc in php

Associate
Joined
4 Mar 2007
Posts
315
Location
United Kingdom
Ok so I have a problem, A class I am developing works flawlessly, however I would like to shorten some commands as the array's I am calling are too long.

Heres the current command to echo an array value:

PHP:
$xml->xmlAR->achievements[0]->achievement[$c]->iconClosed[0]

Is there any way that I can make this short hand. I know that iconClosed will be a constantly reference value, so my natural train of thought was to achieve something like this:

PHP:
$xml->xmlAR->$iconClosed;

but I cannot achieve this as I know it's a string to variable etc.
Is there any other way I can do this?
 
Write a function to extract it for you?

PHP:
function getIconClosed(&$xmlAR)
{
    return $xmlAR->achievements[0]->achievement[$c]->iconClosed[0];
}

$iconClosed = getIconClosed($xml->xmlAR);

Otherwise, no, there isn't, short of extending the class.
 
ahh thought that was bad practice, would you then say write another class containing all of these?
Theres like 20 in total all doing various jobs ofc.

Just tested it works a treat thanks.
 
What does your class do? It sounds like you may need to look at the design if you are having to access data in the way you specified.
 
ahh thought that was bad practice, would you then say write another class containing all of these?
Theres like 20 in total all doing various jobs ofc.

Just tested it works a treat thanks.

Think in terms of how the methods in the class and the type of data fits the sub tasks that a section of code is trying to do. In this particular case since it very much sounds like the variable $iconClosed will have only two states, returning a boolean value and naming the method to indicate this can help writing more fluent code that you will find easier to re-use, refactor or just figure out later on when you forgot why you wrote it in the first place.

Consider:

PHP:
Class Achievements
{
    public function getIconClosed(&$xmlAR)
    {
        return $xmlAR->achievements[0]->achievement[$c]->iconClosed[0];
    }
}

$achievments = new Achievements();
$iconClosed = $achivements->getIconClosed($xml);

If ($iconClosed !== null || !empty($iconClosed) || ... )
{
    // do something
}

Versus

PHP:
Class Achievements 
{
    public function iconIsClosed(&$xmlAR)
    {
        $closed =  $xmlAR->achievements[0]->achievement[$c]->iconClosed[0];
        return (bool)$closed;
    }
}

$achievments = new Achievements();

if ($achivements->iconIsClosed($xml)) {
    // do something
}

They both do the same thing, but the second one is a bit more descriptive and self documenting.
 
Back
Top Bottom