目前,我正在编写一个数据库类,它稍微使用了 PHP 的 PDO 类,但我想添加一些简单的功能,以便更轻松地编写某个应用程序。
现在在下面的一段伪代码中你可以看到我要去哪里。这个例子中唯一的问题是 $result 变量是一个对象,它不能用于比较我在脚本中进一步做的一些东西:
<?php
class Database
{
public function FetchRow ( $query )
{
// .. do some stuff, and make a $result variable
return DatabaseStatement ( $result );
}
}
class DatabaseStatement
{
private $result;
public function __construct ( $query )
{
// .. save result in property etc.
}
public function __get ( $column )
{
// .. check result item
return $this -> result [ $column ];
}
}
$db = new Database;
$result = $db -> Query ( 'SELECT * FROM users WHERE id = 1;' );
if ( $result != null ) // Here $result should be an array OR null in case no rows are returned
{
echo $result -> username; // Here $result should call the __get method
echo '<pre>' , print_r ( $result ) , '</pre>'; // Here $result should be the array, cause it wasn't null just yet
}
正如您所看到的,当我进行比较时,$result 变量不应该是一个对象,我知道可以使用 __toString 将它变成一个字符串。但我希望它是其他类型,主要是数组或空值。
如果可能的话,我怎样才能得到这样的工作(我认为应该有太多的麻烦)?
那么有人可以指出我正确的方向,或者可能给出一段应该可以工作的代码,或者我可以改变以适应我目前的课程吗?