Fairly new to classes in PHP, so bear with me.
class processRoutes
{
//Next line works
private $doc = "works as as string";
//Next line does not work, "Parse error: syntax error, unexpected T_NEW"
private $doc = new SimpleXMLElement('routingConfig.xml', null, true);
private function getTablenames()
{
//do stuff
}
}
I'm trying to ultimately utilize the SimpleXMLElement object within my class, among several private functions. What is the correct method for going about this, and why doesn't my current method work?
You need to do this in your constructor, as this can't be evaluated at this stage of script parsing. 'Simple' values, as strings, bools and numeric values will work though.
class processRoutes
{
//Next line works
private $doc = "works as as string";
private $doc;
public function __construct()
{
$this->doc = new SimpleXMLElement('routingConfig.xml', null, true);
}
// ....
}
anytime you want to reference a class's variable, use the keyword $this
public function getTablenames()
{
$my_new_variable = $this->doc; // Transfers the $doc variable
}
You're attempting to initialise a property with an object instance, but you're only allowed to initialise variables with constants that can be determined at "compile time".
This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
Any initialisation that depends on "run time" knowledge will need to be executed either
$this->doc
,myProcessRoutes->doc = 'some other string'
),myProcessRoutes.initialise_doc('some other string')
, or(Although it's arguable/philosophical if these approaches that occur later than instantiation/constructor are really initialisation).
The point of class constructors/destructors is to provide a "hook" by which the object instance can be initialised/disposed as required.
You might just need to create some specific new instances as per your example, in which case you don't need to accept any input to the constructor from the consumer.
Or, you might need to accept some values in order for your class to be set up properly. This is exactly what's happening in your example code above, when you're calling
private $doc = new SimpleXMLElement('routingConfig.xml', null, true);
(that is, you're passing the values of 'routingConfig.xml'
, null
and true
in to your new instance of SimpleXMLElement
, so that this instance's constructor can initialise the instance using the values you passed to it, ready for use).