PHP function on an html page

Asked

Viewed 501 times

1

Because it doesn’t work:

    </head>

    <body>

     <?php
        include_once '../model/Cliente.php';
        include_once '../DAO/Conexao.php';

        $conexao = new Conexao();
        $cliente = new Cliente();

        $nome = "";
        $fantasia = "";

        //chamando funcaoo
        mostrarCliente();


        /********* FUNÇÃO *****************************************
         * MOSTRANDO CLIENTE ESCOLHIDO *****************************
         ***********************************************************/
        function mostrarCliente() {
            $cliente = $conexao->selectCliente("_ID=10");

            //Se não estiver nulo, então nome recebe nome do cliente
            if (empty($cliente) == FALSE) {
                $nome = $cliente->getNome();
                $fantasia = $cliente->getFantasia();
             }
          }
       ?>
<!-- Texto e caixa - NOME CLIENTE -->
        <label>Nome Cliente</label><br />
        <input type="text" name="nome" size="80px" value="<?php echo $nome; ?>" /><br  />

        <!-- Texto e caixa - NOME FANTASIA -->
        <label>Nome Fantasia</label><br />
        <input type="text" name="nome-fantasia" size="80px" value="<?php echo $fantasia; ?>" /><br />

It only works outside of function. Do I have to instantiate the client object and connection in every function?

  • Just remembering that when using function the external variables are not the same as the internal ones, that is, the variable $name and $fantasia has value of "" in the file, but within the function they are null, because they are different variables.

2 answers

1


Alysson,

The variables $conexao and $cliente must be imported into the function as a whole:

function mostrarCliente() {
        global $cliente, $conexao;
        $cliente = $conexao->selectCliente("_ID=10");
        // (...)

I would transform the function into actually a function, that is, it takes parameter and returns values, the number of lines would be smaller and the code more elegant and dynamic, see:

<?php
    include_once '../model/Cliente.php';
    include_once '../DAO/Conexao.php';

    $conexao = new Conexao();
    $cliente = new Cliente();

    /**
    * @param    string  Recebe nome do método
    * @return   string
    */
    function dadoCliente($get) 
    {
        $cliente = $conexao->selectCliente("_ID=10");

        //Se não estiver nulo, então nome recebe nome do cliente
        if (!empty($cliente)) 
        {
            return $cliente->$get();
        }
        return "";
      }
   ?>

    <!-- Texto e caixa - NOME CLIENTE -->
    <label>Nome Cliente</label><br />
    <input type="text" name="nome" size="80px" value="<?php echo dadoCliente('getNome'); ?>" /><br  />

    <!-- Texto e caixa - NOME FANTASIA -->
    <label>Nome Fantasia</label><br />
    <input type="text" name="nome-fantasia" size="80px" value="<?php echo dadoCliente('getFantasia'); ?>" /><br />

Tip 1

Instead of creating a function whenever displaying data from a client (or other object), you can implement an abstract base class (abstract) with methods in common with their objects such as getNome, getEndereco and then create a child class (ex.: Cliente) which will extend the base class, however, this, with its own properties and methods, example:

class.cliente.base.php

<?php
    public class ClientesBase
    {

        function __construct($id)
        {
            $this->id = $id;
            // restante do código para setar um cliente como query SQL, 
            // etc (que pode inclusive seguir o Query Pattern)
        }

        function getNome() { /* código que recebe o nome */ }
        function getFantasia() { /* código que recebe o a fantasia */ }
    }
?>

class.cliente.php

<?php
    public class Cliente extends ClientesBase
    {
        function getEndereco() { /* código que recebe o endereço */ }
    }
?>

exibe_cliente.php

<?php
    include_once '../model/class.cliente.php';
    include_once '../DAO/Conexao.php';

    $conexao = new Conexao();
    $cliente = new Cliente(10); // onde 10 é o ID

?>

<!-- Texto e caixa - NOME CLIENTE -->
<label>Nome Cliente</label><br />
<input type="text" name="nome" size="80px" value="<?php echo $cliente->getNome; ?>" /><br  />

<!-- Texto e caixa - NOME FANTASIA -->
<label>Nome Fantasia</label><br />
<input type="text" name="nome-fantasia" size="80px" value="<?php echo $cliente->getFantasia; ?>" /><br />

Tip 2

Your connection can (in fact, it’s highly recommended) follow the Pattern Singleton, whose goal is to instantiate only once and this will be available for ALL application.

Singleton Pattern example for Mysql connection

class.database.php

<?php
/*
* Mysql database class - somente uma conexão é permitida
*/
class Database {
    private $_connection;
    private static $_instance; //The single instance
    private $_host = "HOSTt";
    private $_username = "USERNAME";
    private $_password = "PASSWORd";
    private $_database = "DATABASE";

    /*
    Get an instance of the Database
    @return Instance
    */
    public static function getInstance() {
        if(!self::$_instance) { // If no instance then make one
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    // Constructor
    private function __construct() {
        $this->_connection = new mysqli($this->_host, $this->_username, 
            $this->_password, $this->_database);

        // Error handling
        if(mysqli_connect_error()) {
            trigger_error("Failed to conencto to MySQL: " . mysql_connect_error(),
                 E_USER_ERROR);
        }
    }

    // Magic method clone is empty to prevent duplication of connection
    private function __clone() { }

    // Get mysqli connection
    public function getConnection() {
        return $this->_connection;
    }
}
?>

Use demo of Singleton above

<?php
    $db = Database::getInstance();
    $mysqli = $db->getConnection(); 
    $sql_query = "SELECT foo FROM .....";
    $result = $mysqli->query($sql_query);
?>

In your case then, could get the connection:

<?php
    include_once '../model/Cliente.php';
    include_once '../DAO/class.database.php';

    $db = Database::getInstance();
    $conexao = $db->getConnection(); 
    $cliente = new Cliente();

    // (...)
  • Thank you. You helped me a lot.

1

Answering your question: you need to inform that the variable is global, otherwise the function will not find it.

Example

function mostrarCliente() {
        global $cliente;
        $cliente = $conexao->selectCliente("_ID=10");

        //Se não estiver nulo, então nome recebe nome do cliente
        if (empty($cliente) == FALSE) {
            $nome = $cliente->getNome();
            $fantasia = $cliente->getFantasia();
        }
}
  • Don’t forget the name and costume too.

  • Thank you. You helped me a lot.

Browser other questions tagged

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