Daniel Williams
Daniel Williams

Reputation: 2317

Define/set PHP variable

I often get PHP errors about a variable not defined. I'm also wondering what is best practice for setting session variables. Currently I'm doing this:

session_start();

if (!isset($_SESSION["myVar"]))
  $_SESSION["myVar"] = "";

But this seems untidy to me. I know there is a PHP unset function, but what is the equivalent to simply set/define a variable into existence, without setting an initial value?

Upvotes: 0

Views: 230

Answers (1)

jack
jack

Reputation: 1391

Php has dynamic variable allocation and typing. When a variable is first referenced within a program, memory is allocated for its use.

Meaning that unless you don't assign a value, a variable can't be declared, like say, in java.

Best way how to make sure you "declare" all your variables?

  • Assign them to null or empty string at the beginning of each function / method.

About session variables, I'd apply the same logic.

Upvotes: 2

Related Questions