PHP function on an html page

1

Because this does not 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 />

Only works out of function. Do I have to instantiate the client object and the connection in every function?

    
asked by anonymous 30.06.2015 / 22:13

2 answers

1

Alysson ,

The variables $conexao and $cliente should be imported into the function as global:

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

I would turn the function into actually a function, that is, which gets parameter and returns values, the amount 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 you are displaying data from a client (or another object), you can implement an abstract base class ( abstract ) with methods common to your objects such as getNome , getEndereco and then create a child class (eg, Cliente ) that will extend the base class, however, this one, 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 may (in fact, it is strongly recommended) follow the pattern Singleton , whose purpose is to instantiate only once and it will be available to the entire application.

Example Singleton Pattern for connection to MySQL

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;
    }
}
?>

Demo of using the above singleton

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

In your case then, you 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();

    // (...)
    
30.06.2015 / 22:28
1

Answering your question: You need to tell 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();
        }
}
    
30.06.2015 / 22:29