views:

27

answers:

3

Hey folks,

I have got the following issue, my function appends code to a string $string ($string .= bla), but in the beginning the string is empty, so I get this error message

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: $string
Filename: libraries/file.php
Line Number: 90

Of course if I define the string in advance, like $string = NULL, the error would not occur, but but I though maybe there is a way to append to a string without the need to define the variable in advance / having an !empty check.

It should be just a one-line thing, I am looking for a slim code.

Thanks.

+1  A: 

It should still work, its just the interpreter giving you a warning. You can suppress warnings in php if you want with:

error_reporting(E_NONE);

That said its generally its good practice to declare your variables first though, and have warnings enabled while you are testing.

DrDipshit
+1 - And it's not even a warning, just a notice, which is less severe than a warning.
Eric Petroelje
Turning off errors hides problems, doesn't solve them.
Chris
+1  A: 

Slim code and removing all notice level errors don't usually go hand in hand. As you know, the error is about using an uninitialized variable. You can't initialize it without..initializing it.

I wouldn't consider $string = ''; bloat, though.

jasonbar
Well, in contrast it does $string .= bla; vs. $string = NULL; $string .= bla; I am running it through foreach loop, so I have to initialize it inside because in reality it is an array with different keys, so I do not know all the used names.
Lukas Oppermann
A: 

The first time you use a variable just do "=" not ".="

$newVar = ""; //good
$newVar2 .= ""; //bad 

$newVar .= ""; //ok because of good line 
Chris
Thanks, but I know all the things said above.I know why I get the error, I know how to initialize and I know how to hide errors (although, as said aove, hiding is no solution).I was just wondering wether there is a way to write the bad line as a good one.I guess I have to go for the ugly way and initilize.Thanks though.
Lukas Oppermann