简体   繁体   中英

PHP variable won't print before defining it

I'm using a portable WAMP package "USB web server". It is giving error if i try to echo some variable directly, for example

<?php
echo $abc;  
?>

The error i get is: "Notice: Undefined variable: abc "

This will work fine:

<?php
$abc = "foo";
echo $abc;  
?>

Is it possible to fix this error? I am bound to use portable WAMP package as I do no thave administrator privileges, so i can not install any other package.

Well, apart from why I don't know why you would want to echo something that is not defined, you're not getting an error, you're getting a notice.

If you want to do this, you've got to ignore notices in your production environment, like you can read here works like this:

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

What should it print if it is not defined?

You can check if it is defined before you try to print it

if(isset($abc))
{
    echo $abc;
}

You can also suppress the error by appending an @ sign in front of the line

@echo $abc;

But that is not recommended and can be slower.

to remove notice and warning write

error_reporting(E_ALL ^ E_NOTICE); at the top of the page

The variable is indeed not defined. What exactly would you like to happen?

If you don't want to see the error, then define it.

<?php
$abc = '';
echo $abc;
?>

Well, the answer is to fix the code so you aren't accessing variables that have not been defined. If you need to prevent it from printing errors which is not the correct solution (*), then you can switch off notices in your error reporting:

error_reporting(E_ALL ^ E_NOTICE);

The correct solution is to fix the code.

Check if it exists before echoing it

if( isset($abc) ) { echo $abc }

you could of course also just check if the variable exists.

<?php if (isset($myvar)) echo $myvar; ?>

cu Roman

You could also suppress the warning on the echo command. Disabling warnings in general is dangerous.

<?php
    @echo $abc;
?>

One of the earliest principle you learn in programming is to declare your variables . Therefore, to fix this error , declare your variables .

However, it may happen in multiple cases that you don't know if the variable has been defined or not, but still want to avoid the error.

In those cases, check for its existence first:

// print $abc if set, or print an empty string/nothing
echo isset($abc) ? $abc : '';
isset($abc) && print $abc;
if (isset($abc)) echo $abc;

The three lines above will give the exact same result one another.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM