2017-08-14 47 views
0

我想實例化一個PHP類傳遞參數給構造函數,但是當我打印數據的值是空的。沒有問題收到如何從對象內部訪問實例屬性?

傳遞給configuracaoBancoDados.php的POST數據,但是當我從BancoDadosClass.php創建BancoDados class,傳遞參數的構造函數,並嘗試打印使用voltaValor() method所有的數據爲空,此參數。

configuracaoBancoDados.php

<?php 

include("../../../classes/BancoDadosClass.php"); 

if(isset($_POST["acao"]) && $_POST["acao"] == "criarBancoDados") { 
    $host = $_POST["enderecoServidor"]; 
    $nomeBD = $_POST["nomeBD"]; 
    $prefixoTabelasBD = $_POST["prefixoTabelasBD"]; 
    $usuarioBD = $_POST["usuarioBD"]; 
    $senhaBD = $_POST["senhaBD"]; 

    $bancoDados = new BancoDados($host, $usuario, $senhaBD, $nomeBD, $prefixoTabelas); 

    echo $bancoDados->voltaValor(); 

} else { 
    echo "Ação não definida"; 
} 

?> 

BancoDadosClass.php

<?php 

class BancoDados { 

    var $host; 
    var $usuario; 
    var $senha; 
    var $nomeBancoDados; 
    var $prefixoTabelas; 

    var $conexao; 

    function __construct($hostBD, $usuarioBD, $senhaBD, $nomeBD, $prefixoTabelasBD) { 

    $this->host = $hostBD; 
    $this->usuario = $usuarioBD; 
    $this->senha = $senhaBD; 
    $this->nomeBancoDados = $nomeBD; 
    $this->prefixoTabelas = $prefixoTabelasBD; 
    } 

    function voltaValor() { 

    return "Dados: " . $host . " " . $nomeBancoDados . " " . $prefixoTabelas . " " . $usuario . " " . $senha; 
    } 

    function conectar() { 

    $retorno = true; 

    $this->conexao = mysqli_connect($host, $usuario, $senha); 

    if(!$this->conexao) { 
     $retorno = false; 
    } 

    return $retorno; 
    } 

    function desconectar() { 

    mysqli_close($this->conexao); 
    } 
} 

?> 

enter image description here

+2

您需要使用'這 - $> host'等不只是'$ host'等 – Rasclatt

+2

另外,你應該停止寫作「PHP 4」代碼...決定你的類屬性的可見性!鑑於其中一些存儲數據庫證書,他們應該很可能不公開。 – CBroe

+1

自從PHP 4開始,'var'就是傳統的了。使用可見性代替'protected $ host:'等等......你也應該看到你的方法。 –

回答

3

你要打印這樣

function voltaValor() 
{ 
    return "Dados: " . $this->host . " " . $this->nomeBancoDados . " " . $this->prefixoTabelas . " " . $this->usuario . " " . $this->senha; 
} 

在奧德r要訪問對象的範圍內的對象的實例屬性,則需要使用$this->whateverTheNameOfTheVariable

僅供參考,請參閱:

+1

@localheinz感謝您的編輯。 –