我想知道在 php 类中工作时是否可以接受/首选使用 self::method() 和 parent::method() 。
您可以使用 $this->method() 但 $this-> 也可以引用类变量、父类变量或父类中的方法。self:: 中没有歧义
self:: 是否已贬值和/或使用这种风格是否有任何警告或缺点?
我知道 self:: 和 parent:: 是指类的静态实例,但是在 kohana 中,除非您专门将方法定义为静态,否则似乎没有区别。
谢谢。
添加了一个示例:假设此应用程序存储来自多个网站的论坛...
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() 定义为静态时,它才会引发错误。
但正如我所说,我更喜欢使用 self:: 因为从可读性的角度来看,我确切地知道这个函数应该在哪里,而不是使用 $this 会导致歧义,对我来说就是这样。