When Do I Use Static Variables/Functions in PHP

`static` keyword inside function?

It makes the function remember the value of the given variable ($has_run in your example) between multiple calls.

You could use this for different purposes, for example:

function doStuff() {
static $cache = null;

if ($cache === null) {
$cache = '%heavy database stuff or something%';
}

// code using $cache
}

In this example, the if would only be executed once. Even if multiple calls to doStuff would occur.

Is good to use static variable inside a PHP class method

General consensus as far as statics are concerned in PHP is: Avoid, if at all possible. And yes, 99% of the time, it is possible to avoid statics.

Singletons should be avoided 100% of the time. For reasons you can find here and virtually everywhere else on the web. Singletons are like communism: sounds like a nice idea, but when put in to practice, it turns out there's one or two things you didn't anticipate.

A Singletons' main purpouse is to retain state, but PHP itself is stateless, so come the next request, the singleton needs to be re-initialized anyway.

If I write getters like yours, I tend to create them in a lazy-load kind of way:

class Example
{
private $reviewModel = null;//create property
public function getReviewModel()
{
if ($this->reviewModel === null)
{//load once the method is called, the first time
$this->reviewModel = $this->load->model('review_model');
}
return $this->reviewModel;
}
}

This basically does the same thing, without using statics. Because I'm using a property, I still retain the instance, so if the getReviewModel method is called again, the load->model call is skipped, just as it would be using a static.

However, since you're asking about performance as well as coding standards: statics are marginally slower than instance properties: Each instance has a HashTable containing for its properties, and a pointer to its definition. Statics reside in the latter, because they are shared by all instances, therefore a static property requires extra lookup work:

instance -> HashTable -> property
instance -> definition -> HashTable -> property

This isn't the full story, check answer + links here, but basically: the route to a static propery is longer.

As for coding standards: They exist, though still unofficial, most major players subscribe to them, and so should you: PHP-FIG

Things like $this->_protectedProperty; don't comply with the PSR-2 standard, for example, which states, quite unequivocally:

Property names SHOULD NOT be prefixed with a single underscore to indicate protected or private visibility.

PHP and Static Variables in Object Member Functions

  1. This is expected.
  2. This is also the case in C++ (and probably others as well).

You should think of non-static class member functions as if they were just like ordinary functions, but with an implicit $this argument that is automatically provided by the interpreter. (That's exactly how they're implemented in most languages.)

PHP static variables and old data

First of all, static functions and static variables belong to Class not class objects.

Above statement concludes that static variables and methods are always meant to call directly from class e.g. MyClass::function() and MyClass::$var

Static variables in a class never meant to handle a state. So you must never change static variables for a class. use Constants instead.

If you want to store data in a variable, just define a normal (private, protected or public) variable in class and then update it through object of class.

If you are calling callRegistry() in a loop, its wise to reset Helper::$results to an empty array as every user you pass in loop is getting added to Helper::$results. which in turn effects your RAM as all this data is stored as a state until your script is ended.
https://alanstorm.com/php-meminfo-and-memory-leaks/

I think it should solve your issue

class Helper {
private $results = [];

public static askRegistries ($userId) {
$registries = ['registry1','registry2','registry3'];

foreach($registries as $registry) {
self::callRegistry($userId, $registry);
}

return self::$results;
}

private callRegistry($userId, $registry) {
$this->results[] = getData($userId)
}
}

$helper = new Helper();

foreach($userIds as $userId){
$helper->callRegistry($userId, $registry);
}

Why a variable can be static but can not be global in class

What do you need a global declaration for in a class property? We're not dealing with plain functions here. $this->var1 will get you $var1 from any method inside the class, or from an instantiated object outside the class, where the variable is public. But let's be thorough...

Illustrating "Global"

Global has no meaning for class properties; although you can use it with variables inside class methods, just as you can do with regular functions. (But there are more elegant ways to get there; it's better to avoid a load of potentially hazardous clutter in the global scope.) Let's first define a variable:

$globby = 123; // Globby is a friend living outside a function.

A function that doesn't use a global declaration can neither access a variable from outside of its scope, nor change that variable's value. The story goes like this:

function foo() {
echo $globby; // Here we have no clue who globby is?
$globby = 321; // Here we define globby, but then he's totally forgotten. :(
}
foo(); // => 'Notice: Undefined variable: globby'

echo $globby; // => '123' ... still the same old globby.

However, a function that declares a variable as global can both access it and modify it outside the function's scope. Also, a variable newly defined as global inside the function is accessible outside it.

function foot() {
global $globby; // Hey globby, won't you come on in! *Globby UFO Lands*
echo $globby; // - Who are you? - I'm globby that says 123.
$globby = 321; // - But I'm gonna tell you to say 321 everywhere.
}

foot(); // => '123' ... this here is the good old globby from the start.
echo $globby; // => '321' ... see, globby can change outside the function scope!

Illustrating "Static" in Classes

Be aware that static for a class property doesn't work like static for a function variable. Manual: "A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope." And again: "Declaring class properties or methods as static makes them accessible without needing an instantiation of the class." (OOP Static Keyword; and Using Static Variables) Class properties retain their value for the lifetime of the object in any case.

Now, to illustrate the usage (and non-usage) of static and non-static methods (aka. "class functions") and properties (aka. "class variables"). Let's make a little class:

class foo {

static $one = 1; // This is a static variable aka. class property.
var $two = 2; // But this is non-static.

static function say_one() { // This is a static method.
echo self::$one; // Uses self:: to statically access the property.
}

function say_two() { // This is a non-static method.
echo $this->two; // Uses $this-> to dynamically access the property.
}

}

Then let's see what works and what doesn't. Non-working options are commented out.

/* Static Variables and Methods */

echo foo::$one; // => '1'
echo foo::say_one(); // => '1'

// echo foo::$two;
// => "Fatal error: Access to undeclared static property: foo::$two"

// echo foo::say_two();
// => "Strict: Non-static method foo::say_two() should not be called statically.
// & Fatal error: Using $this when not in object context."

/* Non-Static Variables and Methods */

$f = new foo(); // This here is a real effin' instantiated dynamite object. *BOOM*

echo $f->two; // => '2'
echo $f->say_two(); // => '2'

// echo $f->one;
// => "Strict: Accessing static property foo::$one as non static.
// & Notice: Undefined property: foo::$one."

echo $f->say_one(); // => '1'

Hope that clarifies. Note that you can access a static method via an instantiated object, and use that to access a static variable; but you can't directly access static variables as non-static without warnings.

Let me add a note on good practice. If you find that you need to be repeatedly declaring global variables inside your functions, or passing configuration parameters etc. as function arguments, it's a sign that you should probably be factoring your code into a class instead, accessing these globals as its properties. OOP is so much cleaner to work with. You'll code happier. $OOP->nirvana();.

Are static variables in functions in PHP global across instances?

Yes, the static variable will persist across instances of the class.

Example:

<?php

class Test {
public function __construct() {
static $foo;

if ($foo) {
echo 'found';
} else {
$foo = 'foobar';
}
}
}

$test1 = new Test();
$test2 = new Test();
// output "found"

Note that this is true for descendant classes too. If we had a class Child that extended Test, calling parent::__construct (whether explicitly or implicitly) will use the same value of $foo.

Setting a static variable to a function php class

Try this

<?php
function sayhey(){
return 'hey';
};

// my class i do control
class Class1 {

private static $myvar;

public function __construct(){
self::$myvar = sayhey();
//echo '<pre>11 '; print_r(self::$get_cart_contents); echo '</pre>';
}

public static function func1(){
echo '<pre>';
self::$myvar = self::$myvar ?? sayhey();
print_r ( self::$myvar );
echo '</pre>';
}

}// end class

Class1::func1();


Related Topics



Leave a reply



Submit