PHP 5, object living time, private, protected

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
User avatar
9902468
Forum Commoner
Posts: 89
Joined: Thu Jun 06, 2002 6:39 am
Location: Europe

PHP 5, object living time, private, protected

Post by 9902468 »

Hi!

I'm currently developing a set of classes that will be used in the future with PHP 5. I don't have to worry about PHP 4.x compatibility. Now, I've fooled around and there are some things that bug me.

First of all, how long will an instance of a class live? (If it is done like I think then it will die when it is unset or script ends.) If script ends, is the __destruct function always ran or do I have to unset them manually in order to be sure?

Then the other question, what's the difference between private and protected? (If the same as with java then it is so that private methods can't be accessed from child that extends the parent, while protected can be?)

Third

If I do this:

Code: Select all

class test{
    private $number;
    
    function __construct(){
        $this->number=0;
    }
    
    function addOne(){
        $number++;        
    }
    
    function getNumber(){
        return $this->number;
    }
    
    function __destruct(){
        unset($this->number);
    }
    
}
am I accessing the same variable in addOne and __construct, and is the number unset correctly in __destruct?

Also, is a static funtion of any use? (Example please?)

There isn't much info about PHP 5 oop yet, so I've read some Java tutorials. Hopefully somebody here knows. I also feel that the majority of PHP programmers are about to find the wonders of oop, or have just recently, so there should be a big need for PHP oop tutorial. (A proper one, with explanation of the things that I ask above and more, like throw try catch etc. essential)

Thanks,

99
kettle_drum
DevNet Resident
Posts: 1150
Joined: Sun Jul 20, 2003 9:25 pm
Location: West Yorkshire, England

...

Post by kettle_drum »

Well private means that the method can only be used from within the object, so you cant call the method externally. These methods will also not be available to the child class.

And protected means that the method will be passed to child class - but it again cant be called externally.

So theres only a subtle difference to them - but i them seem to be useful in certain situations.

Im not too sure about when the __destruct will be called - weather it will be at the end of the script, or when there are no more references to the object.

Hope this has helped you a bit, and that it hasnt confused you more :)

I found the following link very useful:

http://www.phpvolcano.com/articles/php5 ... stract.php
User avatar
9902468
Forum Commoner
Posts: 89
Joined: Thu Jun 06, 2002 6:39 am
Location: Europe

Post by 9902468 »

Thanks, I think I got it this time.

-99
Post Reply