Search code examples
phpclassvariablesstaticextend

php class and variables


Say I have a class

class person {
    public static function get_pk(){
        return self::$primary_key;
    }
}

and an extended class

class user extends person {
    protected $primary_key = 'id';
}

and I want to run:

echo user::get_pk(); // should echo id

Whenever I run this it fails naturally since $primary_key is not a static variable. How do I get it to return the primary key?

Yes, I can change the class structure, function structure and make it non-static, but for all intents and purposes assume the only thing we can change is the content of the static function get_pk


Solution

  • The only way I can see this done is by declaring the $primary_key variable in the parent class and then assigning a value to it outside of the child class definition scope. (Notice, I've added abstract operators to indicate that the classes are static and capitalized the first letters of the class names to follow the convention.)

    <?
    
    abstract class Person {
        public static $primary_key;
        public static function get_pk() {
            return self::$primary_key;
        }
    }
    
    abstract class User extends Person {
    }
    
    User::$primary_key = 'id';
    echo User::get_pk();
    
    /* End of file */
    

    UPDATE

    Aram, if you want the $primary_key to stay non-static then the method will need to be non-static as well as "the pseudo-variable $this is not available inside the method declared as static" as per the Static Keyword manual.

    Alternatively you could convert your code to use instantiated class objects:

    <?
    
    class Person {
        public function get_pk() {
            return $this->primary_key;
        }
    }
    
    class User extends Person {
        protected $primary_key = 'id';
    }
    
    $user = new User();
    echo $user->get_pk();
    
    /* End of file */