Dan
Dan

Reputation: 4140

PHP - Calling a static function from an extended class

Let's say I have three classes set up as follows:

abstract Class A {

public static function testfunction() 
{
   print_r('Hi');
}

}

Class B extends A {

}

Class C extends A {

}

If I call testfunction through class B or C ie

B::testfunction();

Is there a way of printing out the name of the class that called it? So for example, the output could be

"Hi, this function was called by Class B"

Any advice appreciated.

Thanks.

Upvotes: 0

Views: 535

Answers (2)

halfdan
halfdan

Reputation: 34214

In PHP 5.3 you can use get_called_class() in your static test function. This uses late static binding.

Best wishes, Fabian

Upvotes: 0

troelskn
troelskn

Reputation: 117487

Is there a way of printing out the name of the class that called it?

Yes, in php 5.3, but not in earlier versions.

See: Late Static Binding and get_called_class

In general, you can avoid this problem by using object instances, rather than static classes. It is often a better solution.

Upvotes: 4

Related Questions