Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between static variables and globals in php? [duplicate]

Possible Duplicate:
what is the difference between “GLOBAL” and “STATIC” variable in php

if we create a static variable inside a function, this variable exists in further using of the function... and as far as I know global variable does the same. now what's the benefit of using static variables?

like image 243
Nojan Avatar asked Dec 11 '22 23:12

Nojan


2 Answers

The lexical scope of a static static variable is restricted to the function body – you cannot access the variable outside the function. However, its value will be remembered across multiple calls of the same function.

Global variables exist in global scope and can be accessed from anywhere in your code (you have to use the global keyword or $GLOBALS array inside functions though)

like image 97
knittl Avatar answered Feb 22 '23 22:02

knittl


A static variable just implies that the var belongs to a class but can be referenced without having to instantiate said class. A global var lives in the global namespace and can be referenced by any function in any class. Global vars are always frowned upon because they're so easily misused, overwritten, accidentally referenced, etc. At least with static vars you need to reference via Class::var;

like image 20
Vikas Umrao Avatar answered Feb 22 '23 22:02

Vikas Umrao