我正在编写一个
PHP类,并且包含了一些静态函数,可以快速访问,因为它们很常用,功能也很简单.但是,他们确实使用其中的对象进行数据库访问.我可能会在整个代码中使用静态和非静态上下文中的这些静态方法,因此我希望能够测试是从静态或非静态上下文调用该函数,以便我可以避免创建重复的对象如果从非静态上下文调用该函数(此实例对象和要静态使用的函数中的实例对象).有没有什么方法可以在函数中测试它,以便我可以使用实例对象,如果从非静态上下文调用该函数,并创建它自己的对象,如果从静态上下文调用该函数?
代码示例:
class MyClass { private $db; function __constuct(){ $this->db = new DBConnect(); } public static function myFunction(){ if(/* Is static */){ $db = new DBConnect(); } else { $db =& $this->db; } // Do processing with $db,etc. } }
When a method is declared as static,
not only is the magic variable $this
unavailable (returns NULL),but it is
impossible to tell if the function was
actually called from a static context.
A backtrace implies that for a static
method,calling $object->method() is
internally translated to
className::method() at run time.
原文地址:https://www.jb51.cc/php/131253.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。