rgb192
asked on
new static(), new self()
<?php
//Abstract class HouseholdObject{
//}
class Couch extends HouseholdObject{
Public static function create(){
return new Couch();
}
}
class FlatScreenTV extends HouseholdObject{
Public static function create(){
return new FlatScreenTV();
}
}
class Refrigerator extends HouseholdObject{
Public static function create(){
return new Refridgerator();
}
}
Abstract class HouseholdObject{
Public static function create(){
return new static();
}
}
//class Couch extends HouseholdObject{
//}
class Table extends HouseholdObject{
}
//class Refrigerator extends HouseholdObject{
//}
Couch::create();
Table::create();
echo '<br>end';
from php object oriented tutorial
line 22:
what is the difference between return new static(); and return new self();
The first thing you want to do is look at the data. What do you get when you use var_dump() to print out the return values.
Both are confined to the idea of which object they refer to. self() always refers to the object in which self() is coded. static() refers to the current instantiated (potentially child) version of the original even if that child object does not alter the method of the parent.
Examples from http://php.net/lsb :
Examples from http://php.net/lsb :
<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
self::who();
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
?>
Self refers to the object in which it was coded and will output A.<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // Here comes Late Static Bindings
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
?>
Static refers to the instantiated object and will output B.
ASKER
Code from Barthax works.
How?
Couch::create();
Table::create();
var_dump(Couch::create();)
The first thing you want to do is look at the data. What do you get when you use var_dump() to print out the return values.
How?
Couch::create();
Table::create();
var_dump(Couch::create();)
Wow, good question. I just installed this and ran it, and you don't have any assignment operators, so it creates no data. What did you expect it to do?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
@Barthax: +1 for a great example. I wish EE had a way for us to cause answers like this to percolate up to the top!
Many thanks, Ray_Paseur. If such a feature existed, there's a fair-few of your answers I'd like to have seen at the top too. :)
ASKER
thanks