FUDforum
Fast Uncompromising Discussions. FUDforum will get your users talking.

Home » Imported messages » comp.lang.php » Declaring an array necessary?
Show: Today's Messages :: Polls :: Message Navigator
Return to the default flat view Create a new topic Submit Reply
Re: Declaring an array necessary? [message #184975 is a reply to message #184969] Fri, 21 February 2014 22:03 Go to previous message
Daniel Pitts is currently offline  Daniel Pitts
Messages: 68
Registered: May 2012
Karma:
Member
On 2/21/14 9:56 AM, The Natural Philosopher wrote:
> I was just wondering. Php assumes a varibale exists as soon as it is
> assigned a value, but a function exists to create an array..
> Sop can one just say
>
> $arr['hello']='sexy';
>
> or should there be
>
> $arr=array();
>
> first?
>
>

Necessary, no, but it is still a best practice. It helps with
maintenance later, as well as it clearly states your intent.

Imagine this scenario: You start with

function createMyArray($someData) {

$arr['theData'] = $someData->getX();
$arr['theOtherData'] = $someData->getY();

return $arr;
}


A few weeks later, you get a bug report that you need to only sometimes
add getX().

function createMyArray($someData) {

if ($someData->isFoo()) {
$arr['theData'] = $someData->getX();
}
$arr['theOtherData'] = $someData->getY();

return $arr;
}

Then, you (or someone else) finds out getY() is optional...


function createMyArray($someData) {

if ($someData->isFoo()) {
$arr['theData'] = $someData->getX();
}
if ($someData->isBar()) {
$arr['theOtherData'] = $someData->getY();
}

return $arr;
}


Oh no! You've just introduced a bug where if isFoo and isBar returns
true, then $arr is not set!


Now, if the original author had just added "$arr = []"; things would
have never progressed to this state. It's called defensive programming.
Doing certain things you know aren't strictly necessary now, but might
be necessary, or clear up possible confusion.
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: strpos() before str_replace()? Or, maybe strtr()?
Next Topic: Career Opportunities in Singapore (PHP Tech Lead)
Goto Forum:
  

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ]

Current Time: Sun Nov 24 07:47:10 GMT 2024

Total time taken to generate the page: 0.08002 seconds