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
https://forums.phpfreaks.com/topic/214704-object-lifetime/
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
https://forums.phpfreaks.com/topic/214704-object-lifetime/#findComment-1117100
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
https://forums.phpfreaks.com/topic/214704-object-lifetime/#findComment-1117105
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.