I include class definition and create object inside for loop. If I use include_once(class_file.php) then on the second run of the loop I get exactly the same result I got on first one. If I use include(class_file.php) then I get error “Cannot declare class, because the name is already in use in”
I tried to use unset() to clear object before second iteration but it did not help.
Can/Should I include object within loops? What is appropriate solution?
//run.php
$nominals = array("HFG", "LKD");
for ($x=0; $x<count($nominals); $x++) {
if ( $nominals[$x] == "HFG" ) {
$login = "mark";
$pass = "abc";
$nom = "HFG";
$num = 8495876;
} else if ($nominals[$x] == "LKD") {
$login = "john";
$pass = "gfd";
$nom = "LKD";
$num = 9384757;
} else {
exit();
}
include_once("class_Funding.php");
include('GET_funding_scrape.php');
}
If condition inside of the for loop determines values of login, pass, nom and num. Which are later used included php files.
If I include class outside of the loop I get error that login, pass, nom and num are undefined.
Maybe instead of if I should use cases?
Above file run.php starts entire script.
//class_Funding.php
class DataInfo {
protected $login;
protected $pass;
protected $nom;
public function __construct($login, $pass, $nom) {
$this->login = $login;
$this->pass = $pass;
$this->nominal = $nominal;
}
public function go() {
if ($this->login == "mark") {
return "111111";
} else if ($this->login == "john") {
return "222222";
} else {
return "err";
}
}
}
$object = new DataInfo($login, $pass, $nom);
Above file class_Funding.php contains class definition and initiates $object.
//GET_funding_scrape.php
$new[] = $object->go();
print_r($new);
enter code here
unset($new);
Above file GET_funding_scrape.php gets data from class_Funding.php ads it to array and prints out
My expectation was that on first iteration I get "111111" and second "222222". But I am getting "111111" each time.
class Something { ... };, you need to create an instance of it with$something = new Something();or the like, then use $something in your code. For example, if you have aDoSomethingmethod, after creating your object, you'd use$something->DoSomething();See: Objects in the PHP manual