I am trying to create an class object to a class but I keep getting some unknown error.
This is the “helper class” which it takes content from an XML file
<?php
class helperClass {
private $name;
private $weight;
private $category;
private $location;
//Creates a new product object with all its attributes
function __construct(){}
//List products from thedatabase
function listProduct(){
$xmlDoc = new DOMDocument();
$xmlDoc->load("storage.xml");
print $xmlDoc->saveXML();
}
?>
}
And here I am trying to create an object from the helperClassclass and call the method listProducts from helperClass, but the code it won’t work if I try to instantiate an object of the helperClass
<?php
//Working code...
class businessLogic {
private $helper = null;
public function __construct() {
}
public function printXML() {
$obj = new helperClass();
$obj->fetchFromXMLDocument();
// you probably want to store that new object somewhere, maybe:
$this->helper = $obj;
}
}
}
?>
After the help of you guys I figured it out and this is what I wanted to do
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
require 'businessLogic.php';
$obj = new businessLogic();
$obj->printXML();
?>
</body>
</html>
Your second code snippet is wrong. You can’t evaluate code inside a class def. Only inside the methods of a class.
Try putting the code in the constructor:
This is just an example of how code can be executed on object creation.
Though I wouldn’t actuall use it this way. I’d rather pass the object in or setting it later.
ref: Dependency injection
Once the object is created you can do whatever you want with it. e.g. call methods (which, of course, have to be defined) on it or pass it to other objects.