$model = new static($variable);
All these are within a method inside a class, I am trying to technically understand what this piece of code does. I ran around in the Google world. But can't find anything that leads me to an answer. Is this just another way of saying.
$model = new static $variable;
Also what about this
$model = new static;
Does this mean I'm initializing a variable and settings it's value to null but I am just persisting the variable not to lose the value after running the method?
New static: The static is a keyword in PHP. Static in PHP 5.3's late static bindings, refers to whatever class in the hierarchy you called the method on. The most common usage of static is for defining static methods.
Actually, static variables in PHP are not static at all.. their values can be changed during execution. It's just a shared variable of a class.
A static variable is the attribute of PHP to erase the variable once it finishes its execution and the memory is liberated. However, in some cases, we really want to store the variables even after the fulfillment of function execution.
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(::).
static in this case means the current object scope. It is used in late static binding.
Normally this is going to be the same as using self
. The place it differs is when you have a object heirarchy where the reference to the scope is defined on a parent but is being called on the child. self in that case would reference the parents scope whereas static would reference the child's
class A{
function selfFactory(){
return new self();
}
function staticFactory(){
return new static();
}
}
class B extends A{
}
$b = new B();
$a1 = $b->selfFactory(); // a1 is an instance of A
$a2 = $b->staticFactory(); // a2 is an instance of B
It's easiest to think about self as being the defining scope and static being the current object scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With