PHP - Can an object instance be used across multiple pages?
I've been programming using functions in开发者_如何转开发 the past several years and never really figured out the 'worthiness' of using objects.
My key question is: Can an object in PHP that is instantiated be used across multiple pages or does it die with the page as it is closed?
Even a link to a tutorial would be great!
Anything you create via PHP will cease to exist the moment the page is finished being served, unless you put it in some kind of storage.
The advantage of using objects and OOP is that your code becomes easier to maintain than if you just use a large procedural file. Also, sticking to an MVC framework will also help you separate your project into distinct components.
There are lots of tutorials on the net about using MVC.
It dies as soon as the page ends, same as everything else on the web. The benefits to using objects is in their packagability and reuseability, not in that they can exist across multiple page loads.
The object only exists if it's loaded into the page... include, require, etc. Which is done using the MVC design pattern.
I liked reading "PHP Object-Oriented Solutions". There's code with the book that can be downloaded, and the examples are real-life enough, that the scope of any project can be seen. In other words, "I liked it because most of my projects will benefit, yet most of them are still marketing related, and not extremely large applications, etc.
I coupled the book with learning the CodeIgniter framework, and had as many "Yay"s as "@#$!@#$" moments.
edit: The example in that book uses an Amazon-type site as a base, and expands on the idea of products (as an abstract) vs products (Books, DVDs, etc). The main object would contain all the functions/methods needed to sell an item, but leave the specifics of items to the job of a child class. In the example, the child class for Books needs number of pages. The child class for DVDs needs length.
In sum, the parent class for products must exist in every page, yet the methods that extend it for Books only need to be present on Book specific pages. The same is true for the DVD pages. The advantage to this is that if Magazines should be added to the site, the parent class will work just fine. You only need to write a class that extends the parent specifically for magazines. The parent class will remain untouched.
yes you need to create it each page
If you want to use that object at all page. simple create as separate page then include it at the top
there is explanation about Object http://journals.ecs.soton.ac.uk/java/tutorial/java/objects/object.html
PHP has "shared-nothing" architecture. Objects does not survive the request.
精彩评论