Piter
Piter

Reputation: 61

php - calling static function from a extended class

I cant manage to call a static function (with a constant) from a extended class. Here is my code:

(1st file)
class A
{                        
    function isXSet()
    {
        return X;
    }        
    public static function setX()
    {
        define('X', 1);
    }
}  

(second file)

include('/*first file*/');
class B extends A
{        
    A::setX();        
}

How can i manage to do that ?

Upvotes: 0

Views: 86

Answers (1)

phatskat
phatskat

Reputation: 1815

Your code here

class B extends A
{        
    A::setX();        
}

is a little off. You didn't put your call inside of a method.

class B extends A
{   
    public static function doSomething() {     
        A::setX();
    }
}

This isn't actually doing anything by means of the parent/child relationship. In fact, after you define class A, the call to A::setX() can happen anywhere since it's public and static. This code is just as valid:

class A
{
    function isXSet()
    {
        return X;
    }
    public static function setX()
    {
        define('X', 1);
    }
}

class B { // No extending!
    function isXSet() {
        return A::isXSet();
    }
}

What you're more likely looking for is parent instead:

class A
{
    public function isXSet()
    {
        return X;
    }

    protected static function setX()
    {
        define('X', 1);
    }
}

class B extends A
{   
    public static function doSomething() {     
        parent::setX();
        var_dump( parent::isXSet() ); // int(1)
    }
}

A big plus here is that extending classes can access protected methods and properties from the parent class. This means you could keep everyone else from being able to call A::setX() unless the callee was an instance of or child of A.

Upvotes: 1

Related Questions