PHP Can static:: replace self::?

PhpStatic MethodsStatic Members

Php Problem Overview


I am a little confused with this matter. I am designing an ORM class that tries to behave very similarly to ActiveRecord in ruby on rails, but that's beside the point.

What I'm trying to say is that my class makes extensive use of static attribute inheritance, specially for database and table handling. My question is, should I use self:: at all?

Php Solutions


Solution 1 - Php

You have to ask yourself: "Am I targeting the problem with the adequated approach?"

self:: and static:: do two different things. For instance self:: or __CLASS__ are references to the current class, so defined in certain scope it will NOT suffice the need of static calling on forward.

What will happen on inheritance?

class A {
    public static function className(){
        echo __CLASS__;
    }

    public static function test(){
        self::className();
    }
}

class B extends A{
    public static function className(){
        echo __CLASS__;
    }
}

B::test();

This will print

A

In the other hand with static:: It has the expected behaviour

class A {
    public static function className(){
        echo __CLASS__;
    }

    public static function test(){
        static::className();
    }
}

class B extends A{
    public static function className(){
        echo __CLASS__;
    }
}


B::test();

This will print

B

That is called late static binding in PHP 5.3.0. It solves the limitation of calling the class that was referenced at runtime.

With that in mind I think you can now see and solve the problem adequately. If you are inheriting several static members and need access to the parent and child members self:: will not suffice.

Solution 2 - Php

try to use the code bellow to see the difference between self and static:

<?php
class Parent_{
	protected static $x = "parent";
	public static function makeTest(){
		echo "self => ".self::$x."<br>";
		echo "static => ".static::$x;		
	}
}

class Child_ extends Parent_{
	protected static $x = "child";
}

echo "<h4>using the Parent_ class</h4>";
Parent_::makeTest();

echo "<br><h4>using the Child_ class</h4>";
Child_::makeTest();
?>

and you get this result:

> using the Parent_ class > > - self => parent > - static => parent > > using the Child_ class > > - self => parent > - static => child

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionelite5472View Question on Stackoverflow
Solution 1 - PhpDarkThroneView Answer on Stackoverflow
Solution 2 - PhpRadouane FADELView Answer on Stackoverflow