Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Static Variables

Tags:

php

static

$count = 5; function get_count() {     static $count = 0;     return $count++; } echo $count; ++$count; echo get_count(); echo get_count(); 

I guessed it outputs 5 0 1 and it's right,but I need a better explanation?

like image 495
omg Avatar asked Oct 29 '09 08:10

omg


People also ask

Does PHP have static variables?

Introduction: A static class in PHP is a type of class which is instantiated only once in a program. It must contain a static member (variable) or a static member function (method) or both. The variables and methods are accessed without the creation of an object, using the scope resolution operator(::).

What is difference between static and global variable in PHP?

Global is used to get the global vars which may be defined in other scripts, or not in the same scope. e.g. Static is used to define an var which has whole script life, and init only once.

Can we change static variable value in PHP?

No. Static can be used to declare class variables or within function to declare a variable which persists over function calls, but not over executions of the script.

How can access public static variable in PHP?

Static properties are accessed using the Scope Resolution Operator ( :: ) and cannot be accessed through the object operator ( -> ). It's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g. self , parent and static ). print $foo::$my_static .


1 Answers

The variable $count in the function is not related in any kind to the global $count variable. The static keyword is the same as in C or Java, it means: Initialize this variable only once and keep its state when the function ends. This means, when execution re-enters the function, it sees that the inner $count has already been initialized and stored the last time as 1, and uses that value.

like image 159
soulmerge Avatar answered Oct 05 '22 16:10

soulmerge