views:

107

answers:

3

I am doing a big project in PHP. In PHP you do not need to declare variables. This is causing a lot of problems for me.

In Visual Basic 6, the Option Explicit statement makes it mandatory to declare variables. Is something similar available in PHP?

+3  A: 

If you turn on E_NOTICE error messages, PHP will tell you about uninitialized variables:

ini_set("error_reporting", E_ALL);

Uninitialized is a little bit different than undeclared, but it should give you a similar effect.

Tim Yates
+1 It's also worth noting that `E_ALL` does *not* include `E_STRICT`. So I would do `ini_set("error_reporting", E_ALL `. Also worth noting; You can set `error_reporting` in `php.ini` or in your Apache virtual host definition using `php_value`.
Asaph
+2  A: 
error_reporting(E_ALL);

throws a notice when you attempt to use an undefined variable

a more general tip: use functions instead of global code, and make them small (max. 20 lines). Since variables are local to functions, there's less chance to forget or misspell a variable name.

stereofrog
A: 

Increasing the error reporting level only affects php's behaviour when an undefined variable/element is used as rvalue, like echo $doesnotexist;.
But option explicit on also prohibits the use of undeclared variables as lvalue

Option Explicit On
Dim x As Integer
x = 10
y = 11 ' error, variable is not declared

There's no similar option or config parameter in php.

VolkerK
that's quite logical, because there is no way to declare a variable in php.
stereofrog
There _could_ have been a keyword declared in php5, esp. for classes/members, but there wasn't.
VolkerK