目前我正在編寫一個數據庫類,它稍微使用了PHP的PDO類,但是我想添加一些簡單的功能來使編程某個應用程序變得更容易一些。PHP對象返回值
現在在下面的一段僞代碼中,你可以看到我要去的地方。在這個例子中,唯一的問題是,$ result變量是一個對象,它不能用於一些東西我在做進一步在腳本comparisation:
<?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作爲字符串。但我希望它是一些其他類型,主要是一個數組或null。
如果可能的話,我該如何得到這樣的工作?(應該可能我覺得太麻煩了)?
那麼有人可以指出我正確的方向,或者可能提供一段應該工作的代碼,或者我可以改變以適應當前的課程?
是的,我以前試過這個問題,問題仍然是當你返回$ ds(在你的代碼中)時,它仍然不能使用__get(),並且在使用te類變量時是一個數組。像: $ x = $ y - > FetchRow(); echo $ x; // Array echo $ x - > id; //數據庫的'id'列 – Stefan 2009-06-14 10:03:10
那麼,我用你的解決方案與grossvogel的想法,使用toArray函數,謝謝所有 – Stefan 2009-06-14 12:24:36