Page 1 of 1

PHP access parent array

Posted: Sun Sep 05, 2010 7:20 pm
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>";
		}
	}
?>

Re: PHP access parent array

Posted: Mon Sep 06, 2010 3:55 am
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();

Re: PHP access parent array

Posted: Tue Sep 07, 2010 10:59 am
by wenkep3
How would I structure the website/__construct method to collect everything before rendering