Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php static in if statement

I have a construction like this in my config file:

<?php
if (true) {
    $nonstatic = 1;
    static $config = 1;
}
else {
    $nonstatic = 2;
    static $config = 2;
}

echo $nonstatic;
echo $config;
?>

So why the $config contains 2 if this part of the statement is false and $nonstatic contains 1? Is it a bug?

like image 688
Aldekein Avatar asked Sep 13 '11 16:09

Aldekein


People also ask

What is static :: in php?

The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.

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 self :: in php?

self is used to access static or class variables or methods and this is used to access non-static or object variables or methods. So use self when there is a need to access something which belongs to a class and use $this when there is a need to access a property belonging to the object of the class.

Can static method be private php?

A static private method provides a way to hide static code from outside the class. This can be useful if several different methods (static or not) need to use it, i.e. code-reuse.


1 Answers

I suppose this chunk is being included from a function.

Initialisations of static variables are resolved at compile-time, and if the interpreter finds multiple initialisations, it simply takes the bottom one.

like image 128
MauganRa Avatar answered Oct 04 '22 04:10

MauganRa