Jump to content

[SOLVED] PHP Objects Within Objects


jjacquay712

Recommended Posts

In the JavaScript Document Object Model you can assign a style by doing this:

 

object.style.background-color = "Green";

 

 

I am trying to make something similar that.

 

Here is my php code:

 

class document {
class style {
	var $bg-color = "red";
}

var $doctype;
var $title;
var $body;
var $script;
var $style = new style;

function genoratepage() {
	if ( $this->doctype == "trans" ) {
		echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
	} else if( $this->doctype == "trans")  {
		echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
	}
	echo '<html xmlns="http://www.w3.org/1999/xhtml"><head><title>' . $this->title . '</title>';
	if ( $this->script ) {
		echo "<script type=\"text/javascript\">\n <!-- \n" . $this->script . "\n --></script>";
	}

}
}

 

this code gives me a syntax error Parse error: syntax error, unexpected T_CLASS, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /home/johnj/public_html/class.php on line 3

 

can you declare an object within another object in php?

 

EDIT: i dont think i was clear enough, my revised question is can you have $object->style->bg-color like in js?

Link to comment
https://forums.phpfreaks.com/topic/144136-solved-php-objects-within-objects/
Share on other sites

I do not think in any language you can define a class within a class. In java they use inheritance and extending. PHP does not have "inheritance" yet, but you can extend.

 

But I think you are looking at this the wrong way. Why have a separate class for style? Is there really a need for it? You can just make it a method of "document" and then you can call something like $document->changeStyle($newStyle);

 

You could make it into two seperate classes, without extending or inheritance then have a method called "style" which creates/returns a new style object then something like this may work:

 

$document->style()->setBackgroundColor("#ffffff"); (disregard that)

 

You want to extend the class, if you have document extend style, document will have access to the style class functionality. I would look more into OOP and proper methodology of it.

 

The parse error is because you are defining a class inside of a class.

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.