简体   繁体   English

PHP 在主程序中实例化 class,从函数访问

[英]PHP instantiate class in main program, access from functions

I've got a headache from reading about singletons and patterns and there must be a simpler way...阅读有关单例和模式的内容让我头疼,必须有一种更简单的方法...

I have a nice utility function called log_it($severity,$message) that is used throughout a number of programs.我有一个很好的实用程序 function,称为 log_it($severity,$message),它在许多程序中都使用。 It creates code to append application specific log entries to a shared log on disk.它创建代码到 append 应用程序特定的日志条目到磁盘上的共享日志。 When I load the function once globally (using require) it is available throughout a program, in any function.当我在全局范围内(使用 require)加载 function 时,它在整个程序中可用,在任何 function 中。

I'm converting the application as a whole to object-orientation for various good reasons.出于各种充分的理由,我将应用程序作为一个整体转换为面向对象。 I'd like to create a logger class that has a log_it($severity,$message) method.我想创建一个具有 log_it($severity,$message) 方法的记录器 class 。

I'd like to create the object once, in global scope, and use it from within functions.我想在全局 scope 中创建一次 object,并在函数中使用它。 I'd rather not have to declare the object as global within every function where i want to use it.我宁愿不必在我想使用它的每个 function 中将 object 声明为全局。 In other words I want to emulate the global visibility of the simple non-object function but using a class.换句话说,我想模拟简单的非对象 function 但使用 class 的全局可见性。 What I'd like to do is have $log=new logger() in the main program and then call $log->log_it() from anywhere without any further ado.我想做的是在主程序中有 $log=new logger() ,然后从任何地方调用 $log->log_it() ,不用多说。

Hopefully there is a simple way to do this?希望有一种简单的方法可以做到这一点?

You can declare log_it as an static method.您可以将log_it声明为 static 方法。 And call it from any place u want without needing to instantate the class.并从您想要的任何地方调用它,而无需实例化 class。 like so:像这样:

logger::log_it()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM