0

How can I invoke a function automatically when any static function is called once.

class A{
    private static $val;
    public static function X(){
        return static::$val;
    }
}

class B extend A
{    

}

Is it possible if I call B::X(); then a function can set the value of $val of parent class. This has to be done without creating a instance of class B.

I wanted to do this automatically. something like what construct does. Before any static method is called I want to invoke a function automatically

Ajay Kumar Ganesh
  • 1,838
  • 2
  • 25
  • 33

1 Answers1

0

Is it possible if I call B::X(); then a function can set the value of $val of parent class. This has to be done without creating a instance of class B

Try this:

class A {
    protected static $val;
    public static function X(){
        return static::$val;
    }
}

class B extends A
{
    public static function X(){
        static::$val = 123;
        return parent::X();
    }
}

echo B::X();

You have to

  • Replace private static $val; with protected static $val; to make property visible in class B
  • You have to use extends instead of extend
  • You can use parent:: to call a method of parent class (In your case class A)
mario.van.zadel
  • 2,919
  • 14
  • 23
  • I'm sorry, I guess I wasn't able to convey what exactly I wanted. I wanted to do this automatically. something like what construct does. Before any static method is called I want to invoke a function automatically. – Ajay Kumar Ganesh Nov 20 '15 at 06:26
  • Maybe you should take a look at [aspect-oriented programming](http://stackoverflow.com/questions/242177/what-is-aspect-oriented-programming). – mario.van.zadel Nov 20 '15 at 06:33