【发布时间】:2020-02-25 09:09:46
【问题描述】:
我有一个简单的对象映射实现
class Database
{
protected string $Host = '';
protected string $Port = '';
protected string $Database = '';
protected string $User = '';
protected string $Password = '';
protected object $Instance;
protected string $sql = '';
public function __construct()
{
$this->Host = getenv("DB_HOST");
$this->User = getenv("DB_USERNAME");
$this->Password = getenv("DB_PASSWORD");
$this->Database = getenv("DB_DATABASE");
$this->Port = getenv("DB_PORT");
}
public function connect()
{
$con = mysqli_connect($this->Host, $this->User, $this->Password, $this->Database, $this->Port);
if (mysqli_connect_errno()) {
die($this->getError());
} else {
$this->Instance = $con;
}
return $this->Instance;
}
public function unconnect()
{
if ($this->Instance->close() === false) {
die($this->getError());
}
}
public function getPrimaryKey(string $table)
{
$this->connect();
$this->sql = "SHOW COLUMNS FROM " . $table . ";";
$results = $this->Instance->query($this->sql);
foreach ($results as $row) {
if ($row["Key"] == "PRI") {
$this->unconnect();
return $row["Field"];
}
}
}
}
class ObjectMapping
{
protected string $ClassName = '';
protected object $Database;
protected object $Object;
protected string $PrimaryKey = '';
protected array $ForeignKeys = [];
public function __construct($object)
{
$this->Object = $object;
$this->Database = new Database();
$classPathArray = explode("\\", get_class($object));
$this->ClassName = $classPathArray[count($classPathArray) - 1];
$this->PrimaryKey = $this->Database->getPrimaryKey(strtolower($this->ClassName));
}
public function find(string $id)
{
var_dump($this->Object);
exit;
}
}
class Model
{
protected $Mapper;
public function __construct()
{
$this->Mapper = new ObjectMapping($this);
}
public function find($id)
{
$mappedObject = $this->Mapper->find($id);
return $mappedObject;
}
}
class Coupons extends Model
{
public function __construct()
{
parent::__construct();
}
public function __destruct() {}
}
$coupon = new Coupons();
$coupon = $coupon->find(11);
给定上面的代码,我在转储变量var_dump($this->Object);时出错
这个错误
var_dump(): 还不允许访问属性
在跟踪时,我只会在 Database 类上调用 $this->unconnect(); 时得到这个。
参见方法getPrimaryKey()。
谁有解决办法?
【问题讨论】:
-
顺便说一句,这不是 php 7.4 相关问题。此处仅涉及类型化的属性,这不是导致此问题的原因。
-
除此之外,如果某些对象引用不存在,则此错误将显示
someFunc(&obj) { return $obj; }然后someFunc($users);如果$users不是错误显示的对象。我认为这是检查对象是否完全构建并且它的属性和方法是否可调用的 php 方式。