Page 1 of 1

Reference a global variable from a construct function

Posted: Mon Oct 15, 2007 4:34 am
by jak82
Hey There,

I am wishint to reference the $optionName variable from my construct in within another function.

I can not get this to work ? see the code below

Code: Select all

<?php
class MCQ
{
	public $xml;
	public $optionName;
	public $questionStrap;
	public $questiontype;
	public $num_answers;
	
	function __construct()
	{
		//This loads the xml file in....
		 $xml = simplexml_load_file("path");
		 $optionName = $xml->xpath("/question/options/answer/name");
		 $questionStrap = $xml->xpath("/question/strap");
		 $questiontype = $xml->xpath("/question/type");
		 $num_answers = count($xml->options->answer);
	}
	
	function __destruct()
	{
	}
	
	public function  generateMCQ()
	{
		
                echo $optionName[0];

	}
	
}
?>
The echo works if it is within the construct but fails when it is outside.

I am calling it through

Code: Select all

<?PHP

include("path);
//This creates a noew object of MCQ which is used later
$mcq = new MCQ;

$mcq->generateMCQ();



?>

Any help appreciated,

\Chris

Re: Reference a global variable from a construct function

Posted: Mon Oct 15, 2007 4:46 am
by Christopher
You access the methods and properties of a class from within its methods using $this->.

Code: Select all

<?php
class MCQ
{
	public $xml;
	public $optionName;
	public $questionStrap;
	public $questiontype;
	public $num_answers;
	
	function __construct()
	{
		//This loads the xml file in....
		 $this->xml = simplexml_load_file("path");
		 $this->optionName = $this->xml->xpath("/question/options/answer/name");
		 $this->questionStrap = $this->xml->xpath("/question/strap");
		 $this->questiontype = $this->xml->xpath("/question/type");
		 $this->num_answers = count($this->xml->options->answer);
	}
	
	function __destruct()
	{
	}
	
	public function  generateMCQ()
	{
		
                echo $this->optionName[0];

	}
	
}
?>

Cheers

Posted: Mon Oct 15, 2007 5:06 am
by jak82
Many Thanks Christopher,

Works a treat.