0

I'm building a login class in php that will use sessions. I wanted to know:

  • If an instance of this very class will be saved until it is destroyed, even if I move to another page(without destroying it)?
  • Will I have to rebuild another instance of the class every time (with some saved data in the sessions)?
  • What is the life of a php class?
mario
  • 144,265
  • 20
  • 237
  • 291
Maxime Claude
  • 965
  • 12
  • 27

4 Answers4

1

PHP variables persist while the program is running... just like any other programming language.

Now, how long does the program actually run? We have to distinguish between:

  • The PHP interpreter itself (written in C)
  • Your script (written in PHP)

The PHP interpreter is not designed to share variables between scripts so it doesn't really matter how long it runs.

Your script will run, well, until it's finished: it reaches the last line of finds an exit, die() or return statement. This simple fact should already answer your question. But it's also worth taking into account that there's no point in keeping a PHP script running continuously like a desktop application when it's only used to serve an HTTP request. Unlike other protocols (namely FTP or IRC), HTTP is stateless: each user request starts and closes the connection*.

(*) That's not entirely true (connections can and are normally reused) but doesn't affect the design implications.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
0

Yes, the php class will be destroyed. You can serialize the object and store it in the session, if you choose : Documentation

John C
  • 666
  • 4
  • 8
-1

A PHP object (class instance) acts just like a variable and will be destroyed at the end of the page request. Moreover you cannot store an object in a PHP session. The best you can try is to serialize() it and unserialize() it afterwards to keep your data.

Valentin Mercier
  • 5,256
  • 3
  • 26
  • 50
-1

You should see this per request. If you make a new request when going t another page then yes it needs to be rebuild.

What you could also do is Inversion of control or some sort of register setup. This way you can define it once and return an instance.

Example:

    $ioc->translate(function() {
    # Do stuff load configs. Get data from previous request
    return new \Danoon\Link\Translate('../etc/lang/en_US.php');
});
Dany
  • 735
  • 1
  • 8
  • 27
  • Whats IOC got to do with this question? You are very wrong on this my sir. – Michal Jul 05 '14 at 19:03
  • Because he was talking about instantiating and it can be a pain. This can also help with that repetitive task.So that is why i am not wrong. – Dany Jul 05 '14 at 19:06