Last Updated: February 25, 2016
·
2.076K
· rican7

Checking if a PHP method was called via late-static binding

Sometimes, you might create a static method in an abstract class and want to know if its been called statically via an extending child or not. Its easy to find out. Here's how:

// Are we calling this from an extended class?
$extended = (get_class() !== get_called_class());

Great, that's all fine and dandy.... but what context is that good for? Let's see an example:

<?php

class AbstractModel {

    abstract protected function getPrimaryKey();

    /**
     * Get the SQL-compatible statement for query ordering
     *
     * @param string $direction The direction to order the results in
     * @static
     * @access public
     * @return string
     */
    public static function buildOrderStatement($direction = 'DESC') {
        // Are we calling this from an extended class?
        $extended = (get_class() !== get_called_class());

        if ($extended) {
            $column =  static::getPrimaryKey();
        } else {
            $column = 'id';
        }

        return ($column .' '. $direction);
    }
}

That way, you can still call the method from an external method that doesn't extend the abstract class... that way you don't have to create ridiculous Utils classes. :P

So, this:

echo AbstractModel::buildOrderStatement();

would yield a different result than:

class UserModel extends AbstractModel {
}

echo UserModel::buildOrderStatement();

Get it? Cool. :)