何时以及如何使用 PHP 创建类变量


When and How to make class variables with PHP?

>新手问题,我的类方法中有变量,我是否必须将它们设置为可以使用$this访问它们的类变量?如果没有,请解释何时使用或创建类变量?

private function is_valid_cookie()
{
    $securedtoken = $this->input->cookie('securedtoken');
    // Checks if the cookie is set
    if (!empty($securedtoken)) {
        // Checks if the cookie is in the database
        $s = $this->db->escape($securedtoken);
        $query = $this->db->query("SELECT cookie_variable FROM jb_login_cookies WHERE cookie_variable=$s");
        if ($query->num_rows() != 0) {
            // Now let us decrypt the cookie variables
            $decoded = unserialize($this->encrypt->decode($securedtoken));
            $this->login($decoded['username'], $decoded['password']);
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

正如你们所看到的,我有变量$securedtoken和$decoded = array(),我无法决定是否必须使它们成为类变量并使用$this访问它们

我实际上尝试尽量减少类级变量的使用,以使它们在多个方法中通用,或者它们将从类外的代码引用(直接或通过getter/setter)。 如果变量只是在方法的局部范围内需要,请不要用它污染类。

当您尝试在类中的不同函数中共享这些变量时,您需要创建类变量。然后,您需要为这些属性使用不同的访问修饰符(公共、私有、受保护),具体取决于外部代码是否可以查看它们、子类是否可以查看它们,或者根本不可以查看它们。

您不必将它们设置为实例变量。 您也可以将它们设置为静态变量或常量变量! 使用类变量来描述类的属性。 即一个类有什么。

正确使用术语也很重要。 您询问的是创建变量和实例变量。 类变量 (http://en.wikipedia.org/wiki/Class_variable) 是指静态变量

对于您的特定示例,如果两个变量仅在该函数中使用,则不应使它们成为实例变量。 没有理由在全班共享它们另一方面,如果您需要在其他方法或其他地方再次使用它们,而不是是。你应该。

确定所需的变量类型和访问类型是一项设计决策。

好的起点是面向对象的php概述。 http://php.net/manual/en/language.oop5.php

和基本的初学者教程http://www.killerphp.com/tutorials/object-oriented-php/

是的。您可以像这样声明类变量:

class Dog
{
    protected $name = 'Spot';
    public function getName()
    {
        return $this->name;
    }
}

您可以在文档中阅读有关属性(成员变量)的更多信息。