开发者

PHP instantiate class in main program, access from functions

开发者 https://www.devze.com 2023-03-21 06:10 出处:网络
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

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. It creates code to append application specific log entries to a shared log on disk. When I load the function once globally (using require) it is available throughout a program, in any 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.

I'd like to create the object once, in global scope, and use it from within functions. I'd rather not have to declare the object as global within ever开发者_高级运维y function where i want to use it. In other words I want to emulate the global visibility of the simple non-object function but using a 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.

Hopefully there is a simple way to do this?


You can declare log_it as an static method. And call it from any place u want without needing to instantate the class. like so:

logger::log_it()
0

精彩评论

暂无评论...
验证码 换一张
取 消