【问题标题】:How can I access instance properties from within the object?如何从对象内访问实例属性?
【发布时间】:2017-08-14 20:28:43
【问题描述】:

我正在尝试实例化一个将参数传递给构造函数的 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);
  }
}

?>

【问题讨论】:

  • 您需要使用$this-&gt;host等,而不仅仅是$host等。
  • 另外,你应该停止编写“PHP 4”代码......决定你的类属性的可见性!鉴于其中一些存储数据库凭据,它们很可能不应该是公开的。
  • var 是自 PHP 4 以来的遗留物。改用可见性,例如 protected $host: 等...您还应该在方法上设置可见性。
  • 请阅读phptherightway.com
  • 好的。我会这样做的。

标签: php class constructor


【解决方案1】:

你必须这样打印

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

为了从对象范围内访问对象的实例属性,您需要使用$this-&gt;whateverTheNameOfTheVariable

参考见:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    • 2021-11-07
    • 2019-09-25
    • 2015-06-09
    • 2015-11-09
    • 2022-10-09
    相关资源
    最近更新 更多