如何定义 php 类的全局实例?

发布于 2024-12-28 14:53:21 字数 364 浏览 1 评论 0原文

这是我的代码:

<?php
require_once 'classes/dbconnect.php';
$connector = new dbconnect();
pp();
function pp(){
$uid="0000007";
$table = $connector->query("SELECT * FROM tc_personal WHERE uid = '$uid'");
$tb = mysql_fetch_object($table);
print $tb->name;
}
?>

但是此代码将不起作用,因为 pp() 函数无法访问 $connector。 如何将全局变量定义为 $connector?

This is my code :

<?php
require_once 'classes/dbconnect.php';
$connector = new dbconnect();
pp();
function pp(){
$uid="0000007";
$table = $connector->query("SELECT * FROM tc_personal WHERE uid = '$uid'");
$tb = mysql_fetch_object($table);
print $tb->name;
}
?>

but this code will not work because the pp() function can't access the $connector.
How can i define a global variable as $connector?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

当爱已成负担 2025-01-04 14:53:21

肯定比使用全局变量更好,即使不是 OOP

<?php 
require_once 'classes/dbconnect.php'; 
$connector = new dbconnect(); 
pp($connector); 

function pp($connector){ 
    $uid="0000007"; 
    $table = $connector->query("SELECT * FROM tc_personal WHERE uid = '$uid'"); 
    $tb = mysql_fetch_object($table); 
    print $tb->name; 
} 
?> 

Surely better than using globals, even if not OOP

<?php 
require_once 'classes/dbconnect.php'; 
$connector = new dbconnect(); 
pp($connector); 

function pp($connector){ 
    $uid="0000007"; 
    $table = $connector->query("SELECT * FROM tc_personal WHERE uid = '$uid'"); 
    $tb = mysql_fetch_object($table); 
    print $tb->name; 
} 
?> 
疑心病 2025-01-04 14:53:21
<?php
require_once 'classes/dbconnect.php';
global $connector;
$connector = new dbconnect();
pp();
function pp(){
global $connector;
$uid="0000007";
$table = $connector->query("SELECT * FROM tc_personal WHERE uid = '$uid'");
$tb = mysql_fetch_object($table);
print $tb->name;
}
?>
<?php
require_once 'classes/dbconnect.php';
global $connector;
$connector = new dbconnect();
pp();
function pp(){
global $connector;
$uid="0000007";
$table = $connector->query("SELECT * FROM tc_personal WHERE uid = '$uid'");
$tb = mysql_fetch_object($table);
print $tb->name;
}
?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文