【问题标题】:PHP use variable of class in other classPHP在其他类中使用类的变量
【发布时间】:2015-04-25 23:57:12
【问题描述】:

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

我正在编写一个类来做所有关于帐户管理的事情。 (例如创建新帐户,获取帐户详细信息,检查帐户是否存在......) 在那个类中,我需要做一些 MySQL 请求。因此,我使用的是 medoo-class (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

现在我这样称呼我的班级:

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

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

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

严格标准:以非静态方式访问静态属性 acc::$account

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

最好的,Lox

【问题讨论】:

  • 您的代码中有错字 $accout 应该是 $account 我认为
  • 你是对的——但这不是问题所在。只是更改了变量以便更好地理解。就像以前的 acc tbacc acccnt。

标签: php mysql class variables


【解决方案1】:

我认为您不需要将$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

【讨论】:

  • 感谢您的回答。对不起,但这行不通。行 $database->count("table_accounts", ["column_account" => $this->account]);指 medoo-class 的 $database als 对象。这意味着,如果你使用 $this->account,你会在 medoo-class 而不是 acc-class 中调用 var $account。这就是问题
  • 你试过代码了吗?您正在调用$database 对象(属于medoo 类)的方法count,并且正在将参数传递给该方法,第一个是字符串,第二个是关联数组,其中一个键值对,其值为当前对象$this(属于acc 类)的account 属性。它应该可以工作。
  • 嗯……这听起来很合乎逻辑。等一下。我会再尝试。也许我混淆了其他东西。
  • 比赛的最佳球员!你说的对。我想我只是想办法把它复杂化。
【解决方案2】:

您正在调用一个不存在的变量。

您将 $accout 声明为 public 和 static。

但你尝试调用 $account。

替换:

$my_acc->account = 'Luci';

与:

$my_acc->accout = 'Luci';

【讨论】:

  • 感谢您的快速回答 - 请阅读我对这个问题的最后评论。改变了。
【解决方案3】:

Vex 是对的。去掉static关键字,改用["column_account" => $this->account]

最佳,

B.

【讨论】:

    猜你喜欢
    • 2012-02-03
    • 2017-02-08
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多