Question

I have a sample code in php

class First {
    public static $name;    
    public static function getName() {
       return static::$name;
    }
}

class Second extends First {
    public static $name = 'second';
}

echo Second::getName();  // print 'second'

But when I write it into fuelphp:

File 1:

namespace Model;
use \DB;

class ModelMain extends \Model {
    public static $table_name;

    public static function getName() {
        return self::$table_name;
    }
}

File 2

class Post extends \Model\ModelMain {
    public static $table_name = "post";
}

When I call

Post::getName() // Print null

I expected it will print post. What is wrong with it?

Was it helpful?

Solution

It returns null since the $table_name is not assigned , Instead you should add return static::$table_name; inside the getName() of the ModelMain class to enable the Late Static Binding , so it does displaypost as output.

Late Static Binding...

<?php

namespace Model;
use \DB;

class ModelMain extends \Model  {
    public static $table_name;

    public static function getName() {
        return static::$table_name; //<--- Add static here to introduce LSB
    }
}


class Post extends \Model\ModelMain {
    public static $table_name = "post";
}


echo Post::getName();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top