0

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 ?

7
  • 1
    Possible duplicate of Call parent static method in php Commented Jul 12, 2016 at 18:04
  • 1
    It should work if you call it from somewhere. If you take a look, that A::setX(); is just 'flying around' (it's not inside a method)... Commented Jul 12, 2016 at 18:06
  • @FirstOne - why is this 'flying aroun' ? How can I call that then ? Commented Jul 12, 2016 at 18:10
  • I mean, look at the code. In that place, you define class properties and methods. You don't call stuff in there.. Commented Jul 12, 2016 at 18:11
  • 1
    And a side note, if you call setX() on B, it will call A's method because you extended it (without overriding) Commented Jul 12, 2016 at 18:12

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I think I shoul let You know what I want to do - I want to set constant from a class B, and than check in class A if constant X is set (then do sth) - how can I do that ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.