0

I work with PHP Simple Dom Parser. Actually, I created a test for each tag I want to test like this:

if(count($html->find('section')) == 0){
echo '<p class="pstatus bg-danger"><span class="glyphicon glyphicon-remove"></span>Aucune balise sémantique section.</p>';
}
elseif(count($html->find('section')) >= 1){
echo '<p>Nombre de balises sémantiques section: <span>' . count($html->find('section')) . '</span></p>';    
}

I try to create a function to rewrite all my code to get less lines. I tried this:

function ftest($balise,$balisetxt){
if(count($html->find('$balise')) == 0){
    echo '<p class="pstatus bg-danger"><span class="glyphicon glyphicon-remove"></span>Aucune $balisetxt.</p>';
}
elseif(count($html->find('$balise')) >= 1){
    echo '<p>Nombre de $balisetxt: <span>' . count($html->find('section')) . '</span></p>'; 
}
}

ftest('section', 'balise sémantique section');

But I got these

Notice: Undefined variable: html in E:\xampp\htdocs\testmobile\index.php on line 69

Fatal error: Call to a member function find() on a non-object in E:\xampp\htdocs\testmobile\index.php on line 69

It's like PHP can't access the $html->find thing from PHP Simple Dom Prser within a function. How should I do?

Lucien Dubois
  • 1,590
  • 5
  • 28
  • 53
  • Does this answer your question? [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](https://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) – Syscall Jan 16 '22 at 12:00

2 Answers2

1

$html wont have scope within the function, either pass it as an argument or use the global keyword to get scope. Also $html->find('$balise') should be $html->find($balise).

<?php 
/**
 * find text, yada..
 * @uses $html
 * @param string $balise
 * @param string $balisetxt
 * @return string
 */
function ftest($balise,$balisetxt)
{
    global $html;

    $return = null;

    if(count($html->find($balise)) == 0)
    {
        $return = '<p class="pstatus bg-danger"><span class="glyphicon glyphicon-remove"></span>Aucune '.htmlentities($balisetxt, ENT_QUOTES, "UTF-8").'.</p>';
    } else 

    if(count($html->find($balise)) >= 1)
    {
        $return = '<p>Nombre de '.htmlentities($balisetxt, ENT_QUOTES, "UTF-8").': <span>' . count($html->find('section')) . '</span></p>';
    }
    return $return;
}

ftest('section', 'balise sémantique section');
?>
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

You should learn more about PHP and its scopes: http://www.php.net/manual/fr/language.variables.scope.php (French content as you look to be french)

In a nutshell, A function can't access a variable not defined in it / not passed via a parameter

punkeel
  • 869
  • 8
  • 12