PHP在其他类中使用类的变量

标签 php mysql class variables

我基本上了解 PHP,但我对所有这些类的东西都是新手。现在 - 喜欢它。 这是我的问题:

我正在编写一个类来完成有关帐户管理的所有工作。 (例如创建新帐户,获取帐户详细信息,检查帐户是否存在......) 在该类(class)中,我需要执行一些 MySQL 请求。因此,我正在使用 medoo 类(http://www.medoo.in)。

class acc{

// Attributes
public static $account;
public $pw;
protected $error;

public function acc_exist() {
    $database = new medoo();

    $acc_count = $database->count("table_accounts", ["column_account" => acc::$account]);

    if ($acc_count == 0)  {return true;} else {$this->error .= "Account exists already!";};
}};

请注意这一行:

$database = new medoo();

    $acc_count = $database->count("table_accounts", ["column_account" => acc::$account]);

这里我引入了medoo。 ["column_account"=> acc::$account] 实际上有效。正如我在其他一些帖子中所读到的,我将 $accounts 设置为 public static

现在我这样称呼我的类(class):

$my_acc = new acc();
$my_acc->account = 'Luci';
$my_acc->acc_exist();

我需要那样工作。在我的其余代码的上下文中做一些 acc($account) 是困难的。

但如我所料,我得到一个错误:

Strict Standards: Accessing static property acc::$account as non static

我很清楚,static 保存了 var 的值。所以我需要一些其他的方式。有人有想法吗?

最好的,洛克斯

最佳答案

我认为您不需要将 $account 设置为静态的,这对于您可能使用此代码的方式没有意义,请尝试使用 public $account; 然后使用 ["column_account"=> $this->account]

所以:

class acc{

// Attributes
public $account;
public $pw;
protected $error;

public function acc_exist() {
    $database = new medoo();

    $acc_count = $database->count("table_accounts", ["column_account" => $this->account]);

    if ($acc_count == 0)  {return true;} else {$this->error .= "Account exists already!";};
}};

这里有更多关于如何正确使用 static 的信息:Static Keyword in PHP

关于PHP在其他类中使用类的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29872084/

相关文章:

javascript - 无法为每个输入字段提交右键[单个表单中的多个按钮和输入字段]

php - 平均分配奖杯

php - 使用 PHP 删除数据库中的 li 条目

javascript - 与 Closure Compiler 一起工作的 JavaScript 类的实现

class - 在haskell中定义多类型容器类,麻烦绑定(bind)变量

php - Laravel Voyager 中的密码哈希方法是什么?

php - javascript点击时隐藏div

mysql - 获取mysql查询的第一行

php - 显示 MySQL 数据库的结果数

java - JAVA 如何将构造函数中的值传递给另一个类中的 setter?