Check if a php method is called statically or as an instance method

PHP allows to call you any method of a class both as static and as instance method. Recent version of PHP is more strict though. But still you can call non-static function as static. Calling a non-static function that uses $this statically will cause a fatal error. You’d  want to catch this and throw exception with meaningful message.

If you can determine how this method is called whether statically or as instance method you can handle this situation.

See this example class.

class C {
    private $value = "value";
    public function method () { 
        echo __METHOD__. "\n"; 
        echo "Value:". $this->value. "\n"; 

This method will raise a fatal error you if call it as C::method().

To determine if its this is called statically or as an instance method there are two techniques.

  1. Using debug_backtrace
    1. class A { 
       public function m(){ 
       $bt = debug_backtrace(); 
       throw new Exception(__METHOD__." is called statically");
  2. Using isset on $this.
    1. class A { 
       public function m(){ 
       throw new Exception(__METHOD__." is not called from class instance");


The last one is shorter. But first one is more explicit.

Convert an PHP array to object

How do you convert an php array stdClass object?

Many times, we have to convert array to stdClass objects for easy access. Yeah, easy access. At least for me. Cause typing [“”] instead of -> requires 2 extra key press. I dont like that.

So how do you do it?

Its really simple, just cast the array with (object). It’ll become an stdClass.
See the following code,

$ar = array(
"name"=> "john",
print_r($ar); // will print "Array" as type

// making it an object

$ob = (object) $ar;
print_r($ob); // will print "stdClass Object" as type

// compare the values.
echo "values are identical", PHP_EOL;
echo "values are not identical", PHP_EOL;