PHP Extending class makes children inherit same static property - php

I'd like to start by showing a test case:
class A {
public static $instance=null;
public function __construct(){
self::$instance=$this;
}
public function className(){
return get_class(self::$instance);
}
}
class B extends A {
public function className(){
return get_class(self::$instance);
}
}
// test code
$b=new B();
echo $b->className; // B
$a=new A();
echo $a->className; // A
echo $b->className; // A <- error: not B any more!
Notes
I'm using a factory+singleton patterns above. Well, somewhat.
I don't need any specs on "implementing patterns correctly". I need problem solving, not KISS violations ;).
Critics might say A should be an interface. Ideally, that's what it should have been, but it's just a simple class, sorry.
The issues lies in the fact that self::$instance is the same for all instances. How do I separate self::$instance for each class?
Edit: I've had this idea:
$GLOBALS['store']=array();
class A {
public static $instance=null;
public function __construct(){
$GLOBALS['store'][__CLASS__]=$this;
}
}

You could store an instance per class name:
class A {
public static function getInstance(){
// Maybe use this function to implement the singleton pattern ...
return self::$instance[get_called_class()];
}
public function className(){
return get_class(self::getInstance());
}
}

You can not do this the clean way.
That is one of the mayor drawbacks on stati propertys: you cannot overrride them.
But you wantet an sollution so.....here is the worarround:
use __calllStatic
<?php
class A {
public static function __callstatic($name,$args)
{
if($name="getClass"){
return 'A';
}
}
}
class B extends A{
public static function __callstatic($name,$args)
{
if($name="getClass"){
return 'B';
}
}
}
echo A::getClass();
echo B::getClass();
?>
the output of this is "AB";

You can add a public static $instance=null; declaration in class B.
class A {
public static $instance=null;
public function __construct(){
self::$instance=$this;
}
public function className(){
return get_class(self::$instance);
}
}
class B extends A {
public static $instance=null;
public function className(){
return get_class(self::$instance);
}
}
// test code
$b=new B();
echo $b->className(); // B
$a=new A();
echo $a->className(); // A
echo $b->className(); // Now returns B, as desired.

Related

Get name function in PHP

I have some classes:
class A
{
private $_method;
public function __construct()
{
$this->_method = new B();
}
public function demo()
{
$this->_method->getNameFnc();
}
}
class B
{
public function getNameFnc()
{
echo __METHOD__;
}
}
I'm trying to get the function name of a class B class, but I want the function getNameFnc to return 'demo'. How do I get the name 'demo' in function getNameFnc of class B?
Well, if you really want to do this without passing a parameter*, you may use debug_backtrace():
→ Ideone.com
public function getNameFnc()
{
$backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2);
echo $backtrace[1]['function'];
}
* this would be the recommended way although one should never need to know which function has been previously called. If your application relies on that fact, you have got a major design flaw.
You will need to use debug_backtrace to get that information.
I haven't tested the code below but I think this should give you the information you want:
$callers = debug_backtrace();
echo $callers[1]['function'];
Why not pass it?
class A
{
private $_method;
public function __construct()
{
$this->_method = new B();
}
public function demo()
{
$this->_method->getNameFnc(__METHOD__);
}
}
class B
{
public function getNameFnc($method)
{
echo $method;
}
}
Or use __FUNCTION__ if you don't want the class name.

How to get child class name from parent class

I'm trying to accomplish this without requiring a function on the child class... is this possible? I have a feeling it's not, but I really want to be sure...
<?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(); //returns B
?>
Use get_called_class() instead of __CLASS__. You'll also be able to replace static with self as the function will resolve the class through late binding for you:
class A {
public static function who() {
echo get_called_class();
}
public static function test() {
self::who();
}
}
class B extends A {}
B::test();

Best practice to implement static class inheritance? (singleton)

From php manual:
[...] Static method calls are resolved at compile time.
When using an explicit class name the method is already identified completely and no
inheritance rules apply. If the call is done by self then self is translated to
the current class, that is the class the code belongs to.
Here also no inheritance rules apply [...]
..so im looking for a way to emulate the standard oop inheritance with static singleton.
Code explain better:
// Normal inheritance: my goal.
class Foo{
public function test(){
echo "Foo->test()\n";
}
}
class Bar extends Foo{
public function other_test()
{
echo "Bar->other_test()\n";
}
}
$obj = new Bar();
echo get_class($obj) . "\n";
$obj->test();
$obj->other_test();
/*
Output:
Bar
Foo->test()
Bar->other_test()
*/
// How i would love to do:
class Foo2{
public static function test2()
{
echo "Foo2::test2()\n";
}
// Singleton?
public static $_instance;
public static function get_instance()
{
if(is_null(self::$_instance))
{
self::$_instance = new self();
}
return self::$_instance;
}
}
class Bar2 extends Foo2{
public static function other_test2()
{
echo "Bar2::other_test2()\n";
}
}
$obj2 = Bar2::get_instance();
echo get_class($obj2) . "\n";
$obj2::test2();
$obj2::other_test2();
/*
Output:
Foo2
Foo2::test2()
Fatal error: Call to undefined method Foo2::other_test2()
*/
echo "\n-------\n";
// How im doing actually:
interface Foo3{
public static function get_instance();
}
class Bar3 implements Foo3{
// Singleton?
public static $_instance;
public static function get_instance()
{
if(is_null(self::$_instance))
{
self::$_instance = new self();
}
return self::$_instance;
}
public static function test3()
{
echo "Bar3::test3()\n";
}
public static function other_test3()
{
echo "Bar3::other_test3()\n";
}
}
$obj3 = Bar3::get_instance();
echo get_class($obj3) . "\n";
$obj3::test3();
$obj3::other_test3();
/*
Output:
Bar3
Foo3::test3()
Bar3::other_test3()
*/
The last 'way' force me to avoid the get_instance and static variables to be placed in the parent class, so I do not consider it as a best solution.. if for some reason my get_instance() function will change in the future, i dont want to edit all classes (inheritance! inheritance! we all want inheritance!)
So, is there a way or a best practices to solve this problem?
p.s: php5.3.2
The Singleton pattern in PHP is something like this:
class Singleton {
private static $instance = null;
// Constructor is private, so class cannot be instantiazed from outside
private function __construct() {
}
public static function getInstance() {
if (static::$instance === null) {
static::$instance = new Singleton();
}
return static::$instance;
}
public static function test() {
echo 'Singleton::test()';
}
public function __sleep() {
throw new Exception('Serialization is not alowed.');
}
public function __wakeup() {
throw new Exception('Serialization is not alowed.');
}
public function __clone() {
throw new Exception('Cloning is not alowed.');
}
}
For you is important that keyword static, then this:
class B extends Singleton {
public static function test2() {
echo 'B::test2()';
}
}
$b = B::getInstance();
B::test();
B::test2();
// Singleton::test()
// B::test()
Is this you looking for?

PHP5 static methods inheritance. Overloading. Getting called class name

I have good oop understanding but poor understanding of its implementation in php...
I have the following code, hope it's self documented =).
I need to have BB in the output
class A{
// I can't copy function::classname() to all my descendant classes
static function classname(){
echo __CLASS__;
}
}
class B extends A{
static function test(){
self::classname();
}
function test1(){
self::classname();
}
//i have A LOT of static and non-static functions using self::classname() in their code
// I can't copy all them to base class
}
$v = new B();
B::test();
$v->test1();
I'm stuck with static:: and self:: syntax
PS: another crazy question I've come across:
Suppose I have
function doSomething(){
echo $this->id;
}
Sometimes it gets into the static contexts. Yes, I know, that's because my bad application design. But is it possible to create a second(mirror, overloading) function
static function doSomething(){
echo false;
}
It means that using
$obj->doSomething() returns id and using Class::doSomething() returns false
Question 3:
Is it possible to get property default value in static context an property value in non-static context automatically?
Have a look at late static binding.
class A {
static function classname() {
echo __CLASS__;
}
static function test1() {
static::classname();
}
}
class B extends A {
static function classname() {
echo __CLASS__;
}
}
$v = new B();
B::test1();
$v->test1();
Or as pointed out by Long Ears in the comments, assuming php 5.3.0+ you can use get_called_class()
class A {
static function classname() {
echo get_called_class();
}
// this can be defined in either class A or B without affecting the output
static function test1() {
static::classname();
}
}
class B extends A {
}
$v = new B();
B::test1();
$v->test1();
Outputs:
BB
Regarding your second "crazy" question, see the Magic Methods. Basically, you would need to implement something like:
class Foo
{
public function __call($name, $arguments)
{
// call the _$name function
}
public static function __callStatic($name, $arguments)
{
// call the _{$name}_static function
}
private function _bar()
{
}
private static function _bar_static()
{
}
}
$foo = new Foo();
$foo->bar();
Foo::bar();
it's possible to add a static method like this
class Foo {
public static function __callStatic() {
// ....
}
}
// in Other file
// Call the static method
Foo-->__callStatic()
and call it on an other file (In php ) ?

If i extend a static class in PHP, and the parent class refers to "self::", will this refer to the self in the extended class?

If i extend a static class in PHP, and the parent class refers to "self::", will this refer to the self in the extended class?
So, for example
<?php
Class A
{
static $var
public static function guess(){self::$var = rand(); return $var}
}
Class B extends Class A
{
public static function getVar(){return self::$var}
}
If I ran
B::guess();
then B::getVar();
is the value for Var stored in A::$var or B::$var?
Thank you.
Late static binding was introduced in PHP 5.3, it allows you to control this behavior.
It's easy to test:
class ClassA {
public static function test(){ self::getVar(); }
public static function getVar(){ echo 'A'; }
}
class ClassB extends ClassA {
public static function getVar(){ echo 'B'; }
}
ClassA::test(); // prints 'A'
ClassB::test(); // also prints 'A'
... hope that helps :)
Additional information, usage of self or $this is different into extended classes
class ClassA {
public function test(){ self::getVar(); }
public function test2(){ $this->getVar(); }
public function getVar(){ echo 'A'; }
}
class ClassB extends ClassA {
public function getVar(){ echo 'B'; }
}
$classB = new ClassB();
$classB->test(); // prints 'A'
$classB->test2(); // prints 'B'

Categories