SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Zealot abstraktmedia's Avatar
    Join Date
    Feb 2004
    Location
    Ljubljana
    Posts
    191
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    php, OOP and references

    Hi there...

    I was playing a bit with PHP5 and I found some strange behaviours or I just
    don't understand....

    If I have two classes

    PHP Code:
     
    class A
    {
    function 
    __construct()
    {
         print(
    "A constructor called!<br>");
    }
     
    function 
    __destruct()
    {
         print(
    "A destructor called!<br>");
    }
    }
     
    class 
    B
    {
    function 
    __construct()
    {
         print(
    "B constructor called!<br>");
    }
     
    function 
    __destruct()
    {
         print(
    "B destructor called!<br>");
    }

    to begin with testing I stated:

    PHP Code:
    $a = new A();
    $b = new B(); 
    which gave me a pretty odd output....

    then I tried with references(although that's depricated in php5)
    PHP Code:
    $a = &new A();
    $b = &new B(); 
    in both cases B destructor was called after A destructor.....

    but isn't the one of main rules in OOP that objects have to be destroyed in the order they were created!?

    so I would expect

    A constructor called!
    B constructor called!
    B destructor called!
    A destructor called!

    Any thoughts on that!?
    exit(0);

  2. #2
    SitePoint Wizard DougBTX's Avatar
    Join Date
    Nov 2001
    Location
    Bath, UK
    Posts
    2,498
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by abstraktmedia
    isn't the one of main rules in OOP that objects have to be destroyed in the order they were created!?
    Nope, sorry.

    You might be thinking of the case where A creates B in its constructor, so when A is destroyed B is also destroyed.

    Something like this:

    PHP Code:
    class {
        
        function 
    __construct() {
            print(
    "A constructor called!<br>");
            
    $this->= new B();
        }
        
        function 
    __destruct() {
            
    $this->null;
            print(
    "A destructor called!<br>");
        }
    }

    class 
    {
        
        function 
    __construct() {
            print(
    "B constructor called!<br>");
        }

        function 
    __destruct() {
            print(
    "B destructor called!<br>");
        }
    }

    $a = new A(); 
    Douglas
    Hello World

  3. #3
    SitePoint Zealot abstraktmedia's Avatar
    Join Date
    Feb 2004
    Location
    Ljubljana
    Posts
    191
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    hm...interesting....thanx...
    exit(0);


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •