【问题标题】:Overwrite static variable in fuelphp覆盖fuelphp中的静态变量
【发布时间】:2014-03-25 06:41:03
【问题描述】:

我在 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'

但是当我将它写入fuelphp时:

文件 1:

namespace Model;
use \DB;

class ModelMain extends \Model {
    public static $table_name;

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

文件 2

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

当我打电话时

Post::getName() // Print null

我预计它会打印帖子。它有什么问题?

【问题讨论】:

  • 尝试用return static::$table_name;替换return self::$table_name;
  • 好答案 :) 非常感谢
  • 这是由于静态方法中缺乏多态行为。
  • @hoangvu68,你之前不是已经有答案了吗?
  • :) 抱歉,刚刚接受了您的回答

标签: php static fuelphp


【解决方案1】:

它返回 null 因为 $table_name 没有分配,相反你应该在 ModelMain 类的 getName() 内添加 return static::$table_name; 以启用 Late Static Binding ,所以它确实显示post 为输出。

后期静态绑定...

<?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();

【讨论】:

  • 后期静态绑定!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-22
  • 2016-03-03
  • 2013-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多