0

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?

2
  • Just a normal var or session var? Commented Jan 1, 2018 at 22:11
  • For now, a session var, but I also wonder the best way to be defining variables in PHP. Commented Jan 1, 2018 at 22:18

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So in this case $_SESSION["myVar"] = ""; would be correct?
Yes. If you think your variable type might change in runtime, then maybe assign as null in the beginning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.