0

This code works in my PHP script

$className = 'mission-dates';
$testQuery = $xpath->query("//*[@class='$className']");
echo $testQuery[0]->textContent;

But it doesnt work with a function

$test = returnTextFromClass('mission-dates');
echo $test;

function returnTextFromClass($className)
{
$testQuery = $xpath->query("//*[@class='$className']");
$testQuery = iterator_to_array($testQuery);
return $testQuery[0]->textContent;
}

When I run it through the function it crashes with critical error (wordpress). Any ideas?

cswebd3v
  • 21
  • 1
  • 2

1 Answers1

0

It would help if you also post the error message, but looking at your code, the $xpath variable is undefined in the scope of your function - meaning the function does not know what $xpath is. So I assume an error like Calling query on null or unknown variable $xpath.

If you defined the $xpath outside the method, you need to pass it to the function using use:

function returnTextFromClass($className) use ($xpath) {
   $testQuery = $xpath->query("//*[@class='$className']");
   $testQuery = iterator_to_array($testQuery);
   return $testQuery[0]->textContent;
}

Otherwise you can define $xpath as global variable and then access it in your method using global $xpath.

If you are in an object-environment, bind the $xpath initialization to to $this->xpath = ... and then use it the same way within your method.

marks
  • 1,501
  • 9
  • 24