如何在类中创建动态属性并在PHP中调用它
我有一个类,我想创建一个动态属性(或一个动态变量)来从数据库中收集表列表。这是密码如何在类中创建动态属性并在PHP中调用它,php,pdo,Php,Pdo,我有一个类,我想创建一个动态属性(或一个动态变量)来从数据库中收集表列表。这是密码 include_once($base_dir.'./config/index.php'); class TableList{ private $con; public $Tables_in_sample; public function __construct($con){ $this->conn = $conn;
include_once($base_dir.'./config/index.php');
class TableList{
private $con;
public $Tables_in_sample;
public function __construct($con){
$this->conn = $conn;
}
public function ListTables(){
$query ="SHOW TABLES";
$stmt = $this->connection->prepare($query);
$stmt->execute();
return $stmt;
}
我叫它
include_once($base_dir.'./config/index.php');
include_once('./tablelist.php');
$dbclass = new DBClass();
$conn = $dbclass->getConnection();
$post = new TableList($conn);
$stmt = $post->ListTables();
$count = $stmt->rowCount();
if($count > 0){
echo "<html><body><ul>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo = "<li>".$post->Tables_in_jsonapi."</li>";
}
echo "</ul></body></html>";
}
到
收缴
echo "<html><body><ul>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo = "<li>".$post->Tables_in_sample."</li>"; //here
}
echo“”;
而($row=$stmt->fetch(PDO::fetch\U ASSOC)){
摘录(行);
echo=“- ”$post->Tables\u在样本中。“
”;//这里
}
您不需要动态属性,不需要extract()
,也不需要类TableList
$result = $pdo->query('SHOW TABLES')->fetchAll(\PDO::FETCH_COLUMN);
echo "<html><body><ul>";
foreach ($result as $table) {
echo '<li>' . $table . '</li>';
}
echo "</ul></body></html>";
$result=$pdo->query('SHOW TABLES')->fetchAll(\pdo::FETCH_COLUMN);
回声“”;
foreach($结果为$表){
回显“- ”.$table.“
”;
}
回声“
”;
我认为没有必要上这门课。它没有任何作用。还有,你为什么要提取行?我需要那个类它有它的目的,我只是忘记了这个获取列
,我真的很感谢你的时间。我能问一下你需要那个类做什么吗?@Dharman,这个类实际上是一个模型。也许我看不到整个画面,但在我看来它不像一个模型。无论如何,如果你想继续使用这个类,你应该改进它一点。将fetchAll
移动到方法中并去掉rowCount()
,无论如何都不应在此上下文中使用它。
echo "<html><body><ul>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo = "<li>".$post->Tables_in_sample."</li>"; //here
}
$result = $pdo->query('SHOW TABLES')->fetchAll(\PDO::FETCH_COLUMN);
echo "<html><body><ul>";
foreach ($result as $table) {
echo '<li>' . $table . '</li>';
}
echo "</ul></body></html>";