I'm writing a function for returning a webcrawler, either from a URL or from HTML as a string. I was thinking I could use the same function, split up by providing a "toggle" parameter. I don't know if this is bad practice, but I have used switch and if/else in a similar matter before without incident.
Here is the problematic code:
My function call:
$mainCrawler = $this->_returnCrawler($url, $urlPattern, 'url');
And the function (sanity check included):
public function _returnCrawler($target='', $urlPattern='', $toggle='')
{
if($toggle === 'url'){echo "indeed it is";} //Works as expected
if($toggle === 'url'){ //things break down the line
if(preg_match($urlPattern, $target)){
$client = new Client();
$client->getClient()->setDefaultOption('config/curl/'.CURLOPT_TIMEOUT, 60);
return $crawler = $client->request('GET', $target);
}else{
return false;
}
}
}
As it stands, this makes another function freak out later in the program (function with foreach on HTML elements for getting text, etc).
The error/output:
indeed it is
Fatal error: Call to a member function filter() on a non-object in /www/otherway/application/controllers/Welcome.php on line 267
A PHP Error was encountered
Severity: Error
Message: Call to a member function filter() on a non-object
Filename: controllers/Welcome.php
Line Number: 267
Backtrace:
And the affected line (inside a switch):
$crawler->filter($tag)->each(function ($node) use (&$tagContent, &$n, &$tag) {
$tagContent[$tag][$n] = trim($node->text());
$n++;
});
However, this function gives me the result I want:
public function _returnCrawler($target='', $urlPattern='', $toggle='')
{
if($toggle === 'url'){echo "indeed it is";}
if(true){ //Difference is here
if(preg_match($urlPattern, $target)){
$client = new Client();
$client->getClient()->setDefaultOption('config/curl/'.CURLOPT_TIMEOUT, 60);
return $crawler = $client->request('GET', $target);
}else{
return false;
}
}
}
I have also attempted to wrap it in a Switch/Case, which gives the same bad result.
This really hurts my brain, and I can't see how
if($toggle === 'url'){...}
which evaluates to true and prints the sanity check is any different from
if(true){...}
Also, using
if(1 > 2){...}
gives the expected torrent of errors from functions dependant on the data from this function not getting what they need.
What could cause this? Logic error, blindness?
If nothing else, this could be solved by making different functions, but at this point I'm genuinely curious about what I've done wrong here.
Any help or feedback (on anything in these examples) is greatly appreciated!
Aucun commentaire:
Enregistrer un commentaire