kirk112 Posted January 7, 2011 Share Posted January 7, 2011 Hi Not sure if I am on the right track here but what I am trying to do is set a variable in the parent class and for this to be accessible in the child. class layout { public $site_id; function __construct($site_id) { $this->site_id = $site_id; } function get_flags() { return new flags($this); } function top_nav() { return new top_nav($this); } } class top_nav extends layout { function __construct(){ } function display_site_id() { echo $this->site_id; } } class flags extends layout { function __construct(){ } function display_site_id() { echo $this->site_id; } } $site_id = 1; $layout = new layout($site_id); $flags = $layout->get_flags(); $nav = $layout->top_nav(); var_dump($layout); var_dump($flags); var_dump($nav); This gives me the following output object(layout)#1 (1) { ["site_id"]=> int(1) } object(flags)#2 (1) { ["site_id"]=> NULL } object(top_nav)#3 (1) { ["site_id"]=> NULL } Where I would have expected object(layout)#1 (1) { ["site_id"]=> int(1) } object(flags)#2 (1) { ["site_id"]=> int(1) } object(top_nav)#3 (1) { ["site_id"]=> int(1) } but I am new to OOP and might be doing things completely wrong Thanks for your help Regards Quote Link to comment https://forums.phpfreaks.com/topic/223686-extending-php-class/ Share on other sites More sharing options...
KevinM1 Posted January 7, 2011 Share Posted January 7, 2011 You're confused about inheritance. Just because you pass a layout object to a child object's constructor, that doesn't mean things will automatically be linked up. Walk through the process: 1. You create a new layout with a $site_id of 1. 2. You create a new flags object by calling layout::get_flags(); 2. a. get_flags() passes an instance of the existing layout to the new flags object, but then does nothing with it. The layout object is destroyed. 3. You create a new top_nav object by calling layout::top_nav(); 3. a. the same thing as 2. a. happens - the existing layout object is passed into the new top_nav object, and then immediately discarded. Try: class layout { protected $site_id; public function __construct($site_id) { $this->site_id = $site_id; } public function get_flags() { return new flags($this->site_id); } public function top_nav() { return new top_nav($this->site_id); } } class flags extends layout { public function __construct($site_id) { parent::__construct($site_id); } } class top_nav extends layout { public function __construct($site_id) { parent::__construct($site_id); } } $layout = new layout(1); $flags = $layout->get_flags(); $nav = $layout->top_nav(); Quote Link to comment https://forums.phpfreaks.com/topic/223686-extending-php-class/#findComment-1156287 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.