从函数中调用PHP对象方法
发布时间:2020-12-13 16:46:07 所属栏目:PHP教程 来源:网络整理
导读:我有保护功能,它创建一个类对象 protected function x() { $obj = new classx();} 现在我需要从不同的函数访问类对象的方法(我不想再次初始化). protected function y() { $objmethod = $obj-methodx();} 我怎么能完成它? 哦,这两个函数都存在于同一个类中,
我有保护功能,它创建一个类对象
protected function x() { $obj = new classx(); } 现在我需要从不同的函数访问类对象的方法(我不想再次初始化). protected function y() { $objmethod = $obj->methodx(); } 我怎么能完成它? 哦,这两个函数都存在于同一个类中,说’class z {}’ 错误消息是 Fatal error: Call to a member function get_verification() on a non-object in 解决方法
将$obj(classx的实例)存储在ClassZ的属性中,可能作为私有属性.在ClassZ构造函数或其他初始化方法中初始化它,并通过$this-> obj访问它.
class ClassZ { // Private property will hold the object private $obj; // Build the classx instance in the constructor public function __construct() { $this->obj = new ClassX(); } // Access via $this->obj in other methods // Assumes already instantiated in the constructor protected function y() { $objmethod = $this->obj->methodx(); } // If you don't want it instantiated in the constructor.... // You can instantiate it in a different method than the constructor // if you otherwise ensure that that method is called before the one that uses it: protected function x() { // Instantiate $this->obj = new ClassX(); } // So if you instantiated it in $this->x(),other methods should check if it // has been instantiated protected function yy() { if (!$this->obj instanceof classx) { // Call $this->x() to build $this->obj if not already done... $this->x(); } $objmethod = $this->obj->methodx(); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |