PHP access parent array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
wenkep3
Forum Newbie
Posts: 5
Joined: Fri May 28, 2010 12:24 am

PHP access parent array

Post by wenkep3 »

I'm attempting to put all of my class's content into their parent's array. So far only the __construct method can access the array. If I call a method inside of the construct method, the var will be passed, but otherwise nothing is being passed. So my question is why can the __construct method access the array but no sub-methods?

Code: Select all

<?php
	$body = new body();
	$head = new head();
	$website = new html($head, $body);
	
	$head->title("Paul Wenke");
	
	
	$website->render();

	class html{
		public $contents=array();
		
		function __construct($head, $body){
			$this->contents[]="<html>";
			for($i=0;$i<count($head->contents);$i++){
				$this->contents[]=$head->contents[$i];
			}
			for($x=0;$x<count($body->contents);$x++){
				$this->contents[]=$body->contents[$x];
			}
		}
		function __destruct(){
			$this->contents[]="</body>";
			$this->contents[]="</html>";
		}
		
		function insert($contents){
			$this->contents[]=$contents;
		}
		
		function render(){
			self::__destruct();
			for($i=0;$i<count($this->contents);$i++){
				print($this->contents[$i]."\n");
			}
		}
	}
	
	class head extends html{
		function __construct(){
			$this->contents[]="<head>";
		}
		
		function title($title){
			$this->contents[]="<title>$title</title>";
		}
	}
	
	class body extends html{
		function __construct(){
			$this->contents[]="</head>";
			$this->contents[]="<body>";
		}
	}
?>
User avatar
arrielmabale
Forum Newbie
Posts: 15
Joined: Fri Aug 13, 2010 3:57 pm
Location: Dubai

Re: PHP access parent array

Post by arrielmabale »

head, body and website have their own instance, website is the parent so it doesnt care about head and body's methods.
While head and body inherits html's method.

The cause why you were not able to place you data to your parent is because of the sequence of initialization.

Code: Select all

$body = new body();
        $head = new head();
        $website = new html($head, $body);// created his own instance and invoke the __construct and collected the info
        //already 
        $head->title("Paul Wenke")

        $website->render();
wenkep3
Forum Newbie
Posts: 5
Joined: Fri May 28, 2010 12:24 am

Re: PHP access parent array

Post by wenkep3 »

How would I structure the website/__construct method to collect everything before rendering
Post Reply