inside a computer….Ok, here is my question.
I’m creating a PHP object that will echo out a XML document. I’m putting in a date/time stamp as a default. I’m starting out using the constructor to generate the time stamp.
The roadblock I’ve hit is how to to use different methods to access the XML document that was created inside the constructor. I’m trying to expand my knowledge about OOP so a nudge in the right direction would be appreciated.
<?php //XML DOM OBJECT CREATOR 9000
// Create new DOM object
$dom = new Xmlstuff;
$dom->generateError('This is the error');
$dom->addtime();
$dom->generateXML();
class Xmlstuff extends DOMDocument{
//Constructor
public function __construct(){
//Calling constructor of DOMDocument
parent::__construct('1.0','utf-8');
} //End of constructor
function generateError($errorMsg){
//Generate standard response
//Root Node
$rootNode= $this->createElement('root','');
$this->appendChild($rootNode);
//status Node
$statusNode=$this->createElement('status',' ');
$rootNode->appendChild($statusNode);
//Error Message
$errorElement=$this->createElement('error' ,$errorMsg);
$statusNode->appendChild($errorElement);
//date
$dateElement=$this->createElement('date', date("d/m/Y"));
$statusNode->appendChild($dateElement);
//time
//$timeElement=$this->createElement('time', date("H:i:s").' PST');
//$statusNode->appendChild($timeElement);
}
function addtime(){
//time
$timeElement=$this->createElement('time', date("H:i:s").' PST');
$statusNode->appendChild($timeElement);
}
//Function to display generated XML document
function generateXML(){
header('Content-Type: text/xml');
echo $this->saveXML();
}
} //End of Class
?>
You are extending the DOMDocument, so anything on DOMDocument you want to access is accessible through $this/self Xmlstuff “is a” DOMDocument
Xmlstuff is an extension of DOMDocument. So anything behaviour or data that DOMDocument contains, your new class Xmlstuff also contains.
The call to
parent::__construct();is just saying, after I’ve done specific initialization for the Xmlstuff class, do all the initialization needed for the DOMDocument.Any data/functions declared in the DOMDocument class as public or protected will be inherited by your Xmlstuff class.
Looking further at your code, the addtime function doesn’t have access to $statusNode, if you want access to it (the $statusNode created in generateError), then you need to make it a member variable.
$this->statusNode.Note: you will have to create it as well in the generateError function.
Additionally to make you code tidier, you should initialize $this->statusNode in your constructor. The reason being a class should hide its implementation details (it should be a black box to anyone that wants to use it). If someone called the function
addTime()before callinggenerateError()then$this->statusNodewill not have been created yet.i.e. Add this line to your constructor:
replace this line from
generateError()with