Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP new static($variable)

Tags:

php

static

 $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?

like image 576
Some User Avatar asked Jun 07 '13 06:06

Some User


People also ask

What is new static () in PHP?

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.

Can you change static variable in PHP?

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.

What is the static variable in PHP?

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.

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(::).


1 Answers

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.

like image 149
Orangepill Avatar answered Oct 20 '22 08:10

Orangepill