Welcome Guest, Not a member yet? Register   Sign In
Undefined variable
#1

[eluser]Unknown[/eluser]
Hi Codeigniter Community

I've been coding in Codeigniter for the last couple of weeks - and it really is amazing.

One thing is causing me some problems.

Consider this controller:

Code:
class main_page extends Controller {

    function main_page()
    {
        parent::Controller();
    }

    function index()
    {
                if($variable_name) {
                //Do something intelligent
                }
    }
}

This would trigger the "undefined variable" error. I know $variable_name isn't defined, but as far as I know, this isn't necessary in PHP.
Because of this I have been using the syntax

Code:
if(@$variable_name) {
//Do something intelligent
}

Is there a better way?
#2

[eluser]TheFuzzy0ne[/eluser]
PHP will issue a warning for variables that are called upon, but not set. CodeIgniter is set to show all warnings and errors by default.

Before using a variable that you aren't sure has been set, it's considered good practice to use isset() to confirm that the variable has indeed been set.

Code:
if (isset($variable_name))
{
    // Do something intelligent, without a warning.
}

Another workaround that isn't always as reliable. Simply define your variable at the start of the function. I often do this for clarity, but I don't rely on it throughout my code as a variable can be unset.
#3

[eluser]jtkendall[/eluser]
Something else to remember. Depending on your log settings, the @ only prevents the error from displaying, it's still logged to the CodeIgniter logs, whereas isset() is not.
#4

[eluser]Unknown[/eluser]
Thanks a lot Smile
#5

[eluser]xwero[/eluser]
[quote author="Morvan" date="1234371740"]

Code:
if(@$variable_name) {
//Do something intelligent
}
[/quote]
this is bad use of the @ operator. It suppresses the error message so an error is raised you just don't see it. @ should be avoided as much as possible.

EDIT : i'm too slow.




Theme © iAndrew 2016 - Forum software by © MyBB