2017-08-14 91 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感谢您的编辑。 –