Home  >  Article  >  Backend Development  >  PHP对象有关问题

PHP对象有关问题

WBOY
WBOYOriginal
2016-06-13 12:01:22992browse

PHP对象问题
我写了一个类,比如 class MyClass,
然后我在其中一个页面比如a.php,我实例化 $obj1=new MyClass();
那我的这个已经实例化的对象$obj1能被其它页面引用吗?肯定是不能的。那如果我想在b.php页面里引用,我还需要另外实例化吗?那是不是很麻烦....
------解决方案--------------------
class MyClass  把这个类的方法写成静态方法,这样在每个页面都能直接使用了
 如:MyClass::func();....
------解决方案--------------------
还需要包含一下这个类文件
------解决方案--------------------

<?php<br />#function.php<br />class test{<br />	private static $_instance = NULL;<br />	public function a(){<br />	    echo 'metchod a';<br />	}<br />	public function b(){<br />	    echo 'method b';<br />	}<br /><br />    public static function instance(){<br />        if(self::$_instance === NULL){<br />            self::$_instance  = new self();<br />        }<br />        return self::$_instance;<br />    }<br />}<br /><br />#a.php<br />//include function.php<br />echo test::instance()->a();<br /><br />#b.php<br />//include function.php<br />echo test::instance()->b();

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn