What does new self(); mean in PHP?
self
points to the class in which it is written.
So, if your getInstance method is in a class name MyClass
, the following line :
self::$_instance = new self();
Will do the same as :
self::$_instance = new MyClass();
Edit : a bit more information, after the comments.
If you have two classes that extend each other, you have two situations :
getInstance
is defined in the child classgetInstance
is defined in the parent class
The first situation would look like this (I've removed all non-necessary code, for this example -- you'll have to add it back to get the singleton behavior)* :
class MyParentClass {
}
class MyChildClass extends MyParentClass {
public static function getInstance() {
return new self();
}
}
$a = MyChildClass::getInstance();
var_dump($a);
Here, you'll get :
object(MyChildClass)#1 (0) { }
Which means self
means MyChildClass
-- i.e. the class in which it is written.
class MyParentClass {
public static function getInstance() {
return new self();
}
}
class MyChildClass extends MyParentClass {
}
$a = MyChildClass::getInstance();
var_dump($a);
And you'd get this kind of output :
object(MyParentClass)#1 (0) { }
Which means self
means MyParentClass
-- i.e. here too, the class in which it is written.
With PHP That's why PHP 5.3 introduces a new usage for the
static
keyword : it can now be used exactly where we used self
in those examples :class MyParentClass {
public static function getInstance() {
return new static();
}
}
class MyChildClass extends MyParentClass {
}
$a = MyChildClass::getInstance();
var_dump($a);
But, with static
instead of self
, you'll now get :
object(MyChildClass)#1 (0) { }
Which means that static
sort of points to the class that is used (we used MyChildClass::getInstance()
), and not the one in which it is written.
Of course, the behavior of self
has not been changed, to not break existing applications -- PHP 5.3 just added a new behavior, recycling the static
keyword.
PHP : Difference b/w new self and new object()
"self" is a keyword that references the current class. It is only available inside the class' code.
You can use it to call methods on your own class, but due to binding you can also use it to call methods on a superclass.
Consider the following example:
class TestA {
public static function makeNewInstance() {
return new TestA();
}
}
class TestB extends TestA {
}
Now, calling TestB::makeNewInstance(); will return an instance of TestA. (TestB inherits the method, but it's linked directly to TestA so will still return that)
Compare with this one:
class TestA {
public static function makeNewInstance() {
return new self();
}
}
class TestB extends TestA {
}
Now, calling TestB::makeNewInstance() will return an instance of TestB. (Since self references the active class, and you're calling it on TestB, the contents of "self" is now TestB instead of TestA.
Hope that explains for you. Otherwise, maybe some more detail in your question would help attract more specific answers.
What is the point of using self::$_instance = new self()
The idea is that whenever you call getInstance() throughout your code, you will always get the same instance.
This is useful in some cases where you only want to get access to the same object. Often objects like this might have a private constructor, which effectively forces you to always act on the same instance (also known as a singleton).
Generally people say 'Singletons are evil'. They are good to avoid because they can cause major design issues. In some cases they can still be a good idea though.
Exact difference between self::__construct() and new self()
This is best illustrated in code:
class MyClass {
public $arg;
public function __construct ($arg = NULL) {
if ($arg !== NULL) $this->arg = $arg;
return $this->arg;
}
public function returnThisConstruct () {
return $this->__construct();
}
public function returnSelfConstruct () {
return self::__construct();
}
public function returnNewSelf () {
return new self();
}
}
$obj = new MyClass('Hello!');
var_dump($obj);
/*
object(MyClass)#1 (1) {
["arg"]=>
string(6) "Hello!"
}
*/
var_dump($obj->returnThisConstruct());
/*
string(6) "Hello!"
*/
var_dump($obj->returnNewSelf());
/*
object(MyClass)#2 (1) {
["arg"]=>
NULL
}
*/
var_dump($obj->returnSelfConstruct());
/*
string(6) "Hello!"
*/
return self::__construct()
returns the value returned by the objects __construct
method. It also runs the code in the constructor again. When called from the classes __construct
method itself, returning self::__construct()
will actually return the constructed class itself as the the method would normally do.
return new self();
returns a new instance of the calling object's class.
When should I use 'self' over '$this'?
Short Answer
Use
$this
to refer to the current
object. Useself
to refer to the
current class. In other words, use
$this->member
for non-static members,
useself::$member
for static members.
Full Answer
Here is an example of correct usage of $this
and self
for non-static and static member variables:
<?php
class X {
private $non_static_member = 1;
private static $static_member = 2;
function __construct() {
echo $this->non_static_member . ' '
. self::$static_member;
}
}
new X();
?>
Here is an example of incorrect usage of $this
and self
for non-static and static member variables:
<?php
class X {
private $non_static_member = 1;
private static $static_member = 2;
function __construct() {
echo self::$non_static_member . ' '
. $this->static_member;
}
}
new X();
?>
Here is an example of polymorphism with $this
for member functions:
<?php
class X {
function foo() {
echo 'X::foo()';
}
function bar() {
$this->foo();
}
}
class Y extends X {
function foo() {
echo 'Y::foo()';
}
}
$x = new Y();
$x->bar();
?>
Here is an example of suppressing polymorphic behaviour by using self
for member functions:
<?php
class X {
function foo() {
echo 'X::foo()';
}
function bar() {
self::foo();
}
}
class Y extends X {
function foo() {
echo 'Y::foo()';
}
}
$x = new Y();
$x->bar();
?>
The idea is that
$this->foo()
calls thefoo()
member function of whatever is the exact type of the current object. If the object is oftype X
, it thus callsX::foo()
. If the object is oftype Y
, it callsY::foo()
. But with self::foo(),X::foo()
is always called.
From http://www.phpbuilder.com/board/showthread.php?t=10354489:
By http://board.phpbuilder.com/member.php?145249-laserlight
New self vs. new static
will I get the same results?
Not really. I don't know of a workaround for PHP 5.2, though.
What is the difference between
new self
andnew static
?
self
refers to the same class in which the new
keyword is actually written.
static
, in PHP 5.3's late static bindings, refers to whatever class in the hierarchy you called the method on.
In the following example, B
inherits both methods from A
. The self
invocation is bound to A
because it's defined in A
's implementation of the first method, whereas static
is bound to the called class (also see get_called_class()
).
class A {
public static function get_self() {
return new self();
}
public static function get_static() {
return new static();
}
}
class B extends A {}
echo get_class(B::get_self()); // A
echo get_class(B::get_static()); // B
echo get_class(A::get_self()); // A
echo get_class(A::get_static()); // A
PHP new self() on inherited class is creating a base class object
Use static binding instead.
public static function Get() {
return new static();
}
PHP return new self two vaiables
Since these methods have different signatures I can only assume they are members of different classes, so this is one reason for them calling construct with different arguments.
Also, because you say there is no constructor, I can assume these classes inherit from another class, because a class's constructor can be inherited.
Calling return new self($array);
will always return an instance of the class this statement is defined in.
Calling get_called_class();
will always return the class you are calling from, even if this statement exists in an inherited class.
The way this function is used:
final public static function make(AbstracClass $variable, array $array = array())
{
$Class = get_called_class();
return new $Class($variable, $array);
}
Is the same as:
final public static function make(AbstracClass $variable, array $array = array())
{
return new static($variable, $array);
}
Because self
will always return the class the statement is defined in, and static
will always be the class that is called.
In the class context how to create a new object by new self and new parent?
It simply means that you can use the keyword self
as a shortcut to refer to the class you're in, and the keyword parent
to refer to the class you extended.
class Foo
{
public static function thing()
{
// do something
}
public function method()
{
$foo = new self(); // Creates an instance of Foo
self::thing(); // Statically calls method thing in class Foo
}
}
class Bar extends Foo
{
public function method()
{
$bar = new self(); // Creates an instance of Bar
$bar = new self; // Same thing, without optional parens
$foo = new parent(); // Creates an instance of Foo
parent::thing(); // Statically calls method thing in class Foo
}
}
Related Topics
How to Convert All Images to Jpg Format in PHP
How to Bind an Arbitrary Number of Values to a Prepared Statement in MySQLi
Call to Undefined Function Odbc_Connect() Message While Connecting Sap Hana Database
Get All Orders Ids from a Product Id in Woocommerce
Pushnotification Server Side Implementation
PHP Web Scraping of JavaScript Generated Contents
Mysqli Prepared Statement Column with Variable
MySQL Encryption/Storing Sensitive Data,
Convert Clickable Anchor Tags to Plain Text in HTML Document
How to Debug Why Simplest MySQL Query Returns False
Is MySQLi Extension Enabled in This PHP Configuration
How to Reverse Order Output of a MySQL Query
Get_Result() Doesn't Work Even MySQLnd Is Enabled
Run a Ffmpeg Process in the Background
What Is the Maximum Size of an Array in PHP
PHP Short Circuit Lazy Evaluation, Where Is It in the PHP.Net Manual