sup*_*x12 10 php coding-style kohana
我想知道在php类中工作时使用self :: method()和parent :: method()是否可接受/首选.
您可以使用$ this-> method()但$ this->也可以引用类变量,父类变量或父类中的方法.自我没有歧义::
是自我::折旧和/或使用这种风格是否有任何警告或缺点?
我理解self :: and parent ::引用类的静态实例,但在kohana中,除非你特意将方法定义为static,否则似乎没有区别.
谢谢.
添加了一个示例:假设此应用程序存储来自多个网站的论坛...
class Forum_Controller extends Controller {
    function __construct()
    {
        parent::__construct();
    }
    function index()
    {
        echo self::categories();
    }
/*
 * get a list of categories from a specific site.
 */
    private function categories()
    {
        $db = new Database;
        $categories = $db->query("
            SELECT * FROM
            forum_categories
            WHERE fk_site = '$this->site_id'
        ");
        $view = new View('categories_view');
        $view->categories = $categories;
        return $view;
    }
}
此示例适用于kohana,错误报告设置为:error_reporting(E_ALL&~E_STRICT);
$ this-> site_id在主Controller_Core类(kohana中的库)中定义.
据我所知,$ this不应该是可用的,因为我以静态方式调用self :: categories(),但只有当我将categories()定义为static时才会抛出错误.
但正如我所说,我更喜欢使用self ::因为从可读性的角度来看,我确切地知道这个函数应该在哪里,而不是使用导致歧义的$ this.
小智 6
控制器在Kohana中不是静态的,尽管它们可以包含静态成员变量/方法或常量.
self::是一种写作的简写方式,ClassName::即
class Animal
{
    public static $arms = 0;
}
class Dog extends Animal
{
    public static $leg = 0;
    const NAME = 'dog';
    public static function bark()
    {
        echo 'Woof';
    }
}
要调用静态函数或从类中获取常量,我们使用范围解析运算符::.静态函数是每个类而不是每个对象.Saying ::指的是类的静态实例是错误的,它只是一种访问静态方法的方法 - 没有一个具有这些方法的对象实例.
所以:
Dog::bark(),
Dog::$leg, 
Dog::NAME, 
我们也可以使用
Animal::$arms
在Dog类中我们可以使用self::,parent::所以我们不需要输入完整的类名(因为它可能很长!)
在回答你的问题时:不 - self::不被弃用,使用它也不是不好的做法.它没有在kohana核心中使用的原因是出于一个非常不同的原因....(透明的类扩展,eval下面有关于更多信息的阅读......).
ps静态调用非静态方法是错误的,不应该被允许 - 如果你设置error_reporting(E_ALL | E_STRICT)(就像你应该在开发过程中),你会看到一个错误被引发.
基本上会发生什么:
Core有一个名为的文件:
class Controller_Core { 
    public function someMethod(){}
}
你创建:
// We can use someMethod of Controller_Core
Index_Controller extends Controller {}
这实际上是扩展的,Controller_Core  除非你创建了MY_Controller.php class Controller extends Controller_Core.
//MY_Controller.php
class Controller extends Controller_Core
{
      // overloads Controller_Core::someMethod without us having to change the core file
      public function someMethod(){}
}