Php 是否可以将数据库中表的名称作为我的类的方法?
我非常喜欢使用PDO,所以它可能是开着的 用法可以是:Php 是否可以将数据库中表的名称作为我的类的方法?,php,oop,pdo,Php,Oop,Pdo,我非常喜欢使用PDO,所以它可能是开着的 用法可以是: $m = new MDB(); $m->Users()->GetRec($param); Users()是数据库中表的名称,GetRec($param)是我的函数 我走的路是这样的: class MDB extends DB { function __construct(){ parent::__construct(); if ($result = $this->pdo-&
$m = new MDB();
$m->Users()->GetRec($param);
Users()
是数据库中表的名称,GetRec($param)
是我的函数
我走的路是这样的:
class MDB extends DB {
function __construct(){
parent::__construct();
if ($result = $this->pdo->query("SHOW TABLES"))
{
while ($row = $result->fetch(PDO::FETCH_NUM))
{
// this is only my imagination (not working at all)
__set($row[0],true);
}
}
}
// set
public function __set($name, $value)
{
// here could be a method (not properties)
$this->$name = $value;
}
当然,这一切似乎并不完全是我想要的。所以我能在这个问题上得到一些建议和建议
upd1
谢谢你的神奇方法电话,现在我正努力做到这一点。查看我的更新代码:
class MDB extends DB {
function __construct(){
parent::__construct();
}
public function __call( $method, $param )
{
$tables = array();
if ($result = $this->pdo->query("SHOW TABLES"))
{
while ($row = $result->fetch(PDO::FETCH_NUM))
{
$tables[] = $row[0];
}
}
if (in_array($method,$tables))
{
return $this;
}
else
{
return FALSE;
}
}
嗯,看来对我有用 是的,这是可能的!代码中的错误行是:
__set($row[0],true);
你应该在那里打电话:
$this->$row[0] = true;
看看下面的简单示例和PHP的重载文档
希望这有帮助 请看一下。尽管如果该方法已经存在,则可能会有危险。
class A{
//The array which will contain your data
private $tables;
function __construct($array){
$counter = 1;
foreach($array as $value){
//That's the right call!
$this->$value = $counter++;
}
}
function __set($name, $value){
$this->tables[$name] = $value;
}
function __get($name){
if (array_key_exists($name, $this->tables)) {
return $this->tables[$name];
}
}
}
$array = array('a1', 'a2', 'a3', 'a4', 'a5');
$a = new A($array);
foreach($array as $key){
echo $a->$key;
}