Function not defined error

Asked

Viewed 76 times

2

Follows the code:

<?php
if (isset($_GET['algumacoisa']) && !empty($_GET['algumacoisa'])) {
    $user = "useradmin";
    $pass = "senha123";
    mysql_connect("localhost", $user, $pass);
    mysql_select_db("meubancodedados");
    $consulta    = mysql_query("select * from teste where Status= '' ");
    $total       = 0;
    $atualizadas = 0;
    while ($linha = mysql_fetch_assoc($consulta)) {
        $total += 1;
        $idpedido = $linha["Pedido"];
        if (verifica($idpedido))
            $atualizadas += 1;
    }
    function verifica($pedido) // Inicio Function Verifica
    {
        // Email cadastrado no Pagamento Digital
        $email       = "[email protected]";
        // Obtenha seu TOKEN entrando no menu Ferramentas do Pagamento Digital
        $token       = "1231232132131";
        $urlPost     = "https://www.pagamentodigital.com.br/transacao/consulta/";
        $transacaoId = $pedido;
        $pedidoId    = $pedido;
        $tipoRetorno = 1;
        $codificacao = 1;
        $ch          = curl_init();
        curl_setopt($ch, CURLOPT_URL, $urlPost);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, array(
            "id_transacao" => $transacaoId,
            "id_pedido" => $pedidoId,
            "tipo_retorno" => $tipoRetorno,
            "codificacao" => $codificacao
        ));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Authorization: Basic " . base64_encode($email . ":" . $token)
        ));
        /* XML ou Json de retorno */
        $resposta = curl_exec($ch);
        /* Capturando o http code para tratamento dos erros na requisição*/
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($httpCode != "200") {
            echo $httpCode;
            echo "algum erro ocorreu.. tente novamente!";
        } else {
            $xml       = simplexml_load_string($resposta);
            $codstatus = $xml->cod_status;
            $email     = $xml->cliente_email;
            $nome      = $xml->cliente_nome;
            $meio      = $xml->cod_meio_pagamento;

            if ($meio != 10) {

                $meio = "Cartao";
            }
            if ($codstatus == 3) {
                mysql_query(" UPDATE teste SET Status = 'Aprovado' WHERE Pedido = '$pedido' ");
                mysql_query(" UPDATE teste SET Email = '$email' WHERE Pedido = '$pedido' ");
                mysql_query(" UPDATE teste SET Nome = '$nome' WHERE Pedido = '$pedido' ");
                mysql_query(" UPDATE teste SET Meio = '$meio' WHERE Pedido = '$pedido' ");
                return true;
            }

        }
    } // Fim function verifica



    echo "<xml><total>{$total}</total>
<atualizadas>{$atualizadas}</atualizadas></xml>";


} else {

    echo "<meta charset='utf-8'/> Página inválida, movida temporariamente.";
}

?>

Problem is, there’s this mistake: Fatal error: Call to Undefined Function verifies() in /home/domain/public_html/Ctr/actualiz.php on line 13 The line pointed there is this:

if ( verifica($idpedido) ) 

Summarizing why I came here.. if I take this IF/ELSE(the one that checks if there was a GET request on the page), it works again without problems. Yes, I’m getting a get on the page, something like . php? someway=test, for my page to enter, but then that gives the error.

Why is it, it doesn’t make sense to me!

1 answer

4


I couldn’t understand your code very well, and I don’t know if it influences PHP, but try to declare the function before calling it. As directed by @bfavaretto you are declaring your function within the if (isset($_GET['algumacoisa']) && !empty($_GET['algumacoisa'])) {

Recommended is that you declare the function outside the if(), so that it exists independent of what if().

if ( verifica($idpedido) ) 
     $atualizadas+=1;
}
function verifica($pedido) {

Try it like this:

<?php
function verifica($pedido) // Inicio Function Verifica
    {
    ...
    }
if(isset($_GET['algumacoisa']) && !empty($_GET['algumacoisa']))
   {
   ... Aqui dentro você faz a chamada da função verifica().
   }
php?>

If you declare a function within if it will only exist if the if condition is satisfied. Example:

<?php

$criarFuncao = true;

funcao1(); //Essa função será chamada pois mesmo ela sendo declarada no final do código ela sempre será declarada.

if($criarFuncao) {
    function funcao2() {
        echo "A função 2 só será criada quando a condição if($criarFuncao) for satisfeita.";
   } 
}

if($criarFuncao) funcao2(); //Se a condição $criarFuncao for verdadeira, a função será criada no if anterior, e poderá ser chamada na condição atual.

function funcao1() {
    echo "Funcao 1 é criada independente de qualquer condição e pode ser chamada antes ou depois da declaração.";
}

php?>

Credits:

User-defined functions documentation and Comments from bfavaretto.

  • 1

    In the author’s code, the function is declared within a if. In such cases you are right, it needs to be stated before it is called. But you wouldn’t need it if you were outside the if. Confused? PHP!

  • 1

    At ease. Also worth a look to fill the answer: http://php.net/manualen/functions.user-defined.php. (see example 2).

  • 2

    Deep down, I can’t see a good reason to declare a function within a if. Changing that would also solve the problem.

  • 2

    Respsota edited, I think it’s better now, if I have said some nonsense correct me. And also really do not see a good reason to declare a function within an if.

  • I read this link that the bfavaretto indicated, and there it is clear that the function does not need to be declared before the use of it, except in conditional cases, which is the case of the use of IF/ELSE.. Regarding the problem, I declared before the condition and picked up perfectly. Thanks to all!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.