全局PHP类中的函数? [英] Global PHP class in functions?

查看:49
本文介绍了全局PHP类中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在PHP函数中访问类的一个实例?像这样:

Is there a way to access one instance of a class inside functions in PHP? Like this:

include("class.php");
$bla=new Classname();

function aaa(){
    $bla->DoSomething();  //Doesn't work.
}

$bla->DoSomething();  //Works.


推荐答案

如果我正确解释了您的问题,那么正确的方法

If I interpret your question correctly, then the proper way to do this is create a singleton class.

class Singleton {
    private static $instance;

    private function __construct() {}
    private function __clone() {}

    public static function getInstance() {
        if (!Singleton::$instance instanceof self) {
             Singleton::$instance = new self();
        }
        return Singleton::$instance;
    }

    public function DoSomething() {
        ...
    }
}

您将在函数中按以下方式调用此函数:

You would call this in your function as follows :

function xxx() {
    Singleton::getInstance()->DoSomething();
}

这篇关于全局PHP类中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆