开发者

instantiate a class object once and have the information globally available?

is it possible to only instantiate my class once and have the data that has been passed into my class available globally?

In my case I have a class called Mail and I'm instantiating it once on my main page. How can I get the information gathered by the methods available to other parts of my site without having to make a new Mail object?

On some of my files, i need to re inc开发者_如何学编程lude the Mail.class.php because they are outside the scope of the main include php page. But vital information has already been gathered into the already created object Mail. I need to access that information, and I don't want to dump the information into sessions either.


Consider using a Dependency Injection container. The basic principle is what you are describing: define an instance of a class as a service in your container, and allow it to be used from anywhere in your code that has access to the container.

The Symfony framework's DI component is available as a separate component, or you can check out Pimple as a lightweight example. These are two that I use; I'm sure there are many others.


Two options I can think of...

1) Use globals, do NOT do this. 2) Make your mail class a singleton, so whenever you instantiate it, you have the data you set.


is it possible to only instantiate my class once and have the data that has been passed into my class available globally?

Yes, that's possible. Once you instantiated your class, it's an object assigned to a variable. You can pass that variable along in your program and then you have access to the object.

In my case I have a class called Mail and I'm instantiating it once on my main page. How can I get the information gathered by the methods available to other parts of my site without having to make a new Mail object?

This is called dependency injection, other parts of your site have a dependency on objects of even other parts of your site. So you need to inject that dependency, e.g. as a function parameter for a simple example:

Main page:

$mail = new Mail;
other_part($mail);

Other part:

function other_part(Mail $mail)
{
     $mail; # there you have it
}


you can post the object in json format to other pages or you could make a temporary file/dbtable to hold the info. or sessions but that was not an option ;-). don't think its possible to do it in an other way. but hey, I'm not an expert.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜