Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what means new static? [duplicate]

Tags:

php

I saw in some frameworks this line of code:

return new static($view, $data); 

how do you understand the new static?

like image 564
Hello Avatar asked Apr 09 '13 09:04

Hello


People also ask

What is new static?

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.

What does static mean in code?

What does static mean? When you declare a variable or a method as static, it belongs to the class, rather than a specific instance. This means that only one instance of a static member exists, even if you create multiple objects of the class, or if you don't create any. It will be shared by all objects.

What does static mean in CS?

Static is another term used to describe constant. For example, many web pages are static web pages HTML pages, which means none of the content being displayed was generated by other code or a script. Static pages do not change unless the creator manually makes a change to the file and looks the same to all visitors.

What does it mean for a class to be static?

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new operator to create a variable of the class type.


1 Answers

When you write new self() inside a class's member function, you get an instance of that class. That's the magic of the self keyword.

So:

class Foo {    public static function baz() {       return new self();    } }  $x = Foo::baz();  // $x is now a `Foo` 

You get a Foo even if the static qualifier you used was for a derived class:

class Bar extends Foo { }  $z = Bar::baz();  // $z is now a `Foo` 

If you want to enable polymorphism (in a sense), and have PHP take notice of the qualifier you used, you can swap the self keyword for the static keyword:

class Foo {    public static function baz() {       return new static();    } }  class Bar extends Foo { }  $wow = Bar::baz();  // $wow is now a `Bar`, even though `baz()` is in base `Foo` 

This is made possible by the PHP feature known as late static binding; don't confuse it for other, more conventional uses of the keyword static.

like image 55
Lightness Races in Orbit Avatar answered Sep 29 '22 11:09

Lightness Races in Orbit