Reference a global variable from a construct function

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
jak82
Forum Newbie
Posts: 11
Joined: Mon Oct 15, 2007 4:21 am

Reference a global variable from a construct function

Post 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
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Reference a global variable from a construct function

Post 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];

	}
	
}
?>
(#10850)
jak82
Forum Newbie
Posts: 11
Joined: Mon Oct 15, 2007 4:21 am

Cheers

Post by jak82 »

Many Thanks Christopher,

Works a treat.
Post Reply