Jump to content

Object lifetime


Wtower

Recommended Posts

Let assume:

 

class b {
    public $varb;
    function __construct() {
        $varb = 'something';
    }
}
class a {
    public $vara;
    function __construct() {
        $vara = new b();
    }
}
$obj = new a();
echo($a->$vara->$varb); // Fatal error: cannot access empty property

 

Obviously, the lifetime of object $vara of class b ends at the end of constructor of a. I can understand why, but coming from a cpp background I find this inconvenient.

 

Do I miss something? Is there some operator instead of new, that determines the lifetime? What object oriented alternative approach would you recommend.

 

Thanks for the help.

 

Regards

Link to comment
Share on other sites

Ah, my mistake. Classic syntax bug. Line 4 should be like:

$this->varb = 'something';

And last line:

echo $obj->vara->varb;

 

Yep, when in the context of itself you access properties of a class by using either self:: or $this, cool that you sorted that out though...

 

Admittedly, $this->varname used to catch me out a few years back, but you soon get into the swing of things.

 

Though I don't see the need for the $ prefixing the echo, and the parenthesis can be omitted too ;)

 

Rw

Link to comment
Share on other sites

Great  :)

 

Well, the $echo was a syntax error of my reply! Anyway. Thanks for the attention. I am basically no more than a sunday-programmer but I hope my very new project in php, which i rewrite from visual cpp for the needs of my small business, will evolve into a nice round open source project.

 

Best Regards

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.