【问题标题】:PHP, error set static variable for class instance inside classPHP,错误为类内的类实例设置静态变量
【发布时间】:2016-03-26 18:50:13
【问题描述】:

我正在尝试在另一个类中调用类方法。

<?php
class A {
    public static $instant = null;
    public static $myvariable = false;

    private function __construct() {}

    public static function initial() {
        if (static::$instant === null) {
            $self = __CLASS__;
            static::$instant = new $self;
        }
        return static::$instant; // A instance
    }
}

class B {
    private $a;

    function __construct($a_instance) {
        $this->a = $a_instance;
    }

    public function b_handle() {
        // should be:
        $this->a::$myvariable = true;
        // but:
        // Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)

        // try with:
        // $this->a->myvariable = true;
        // but:
        // Strict Standards: Accessing static property A::$myvariable as non static
    }
}

// in file.php
$b = new B(A::initial());
$b->b_handle();

var_dump(A::$myvariable);

目前,我的替代方案是:

<?php
class A {
    public function set_static($var,$val) {
        static::$$var = $val;
    }
}

所以:

$this->a->set_static('myvariable',true);

我该怎么办? 发生了什么? 我错了吗?

为什么我不能直接从 B 类将 myvariable 设置为静态变量?

抱歉英语不好。

【问题讨论】:

  • 这是非常不寻常的代码,我认为这里有几个问题让您和其他可能的回答者感到困惑。尝试将其放入 B__construct() 方法中,您会立即看到以下几个问题之一:var_dump($a_instance); 我得到了 NULL 打印出来,因此您的代码没有按照您的想法执行。
  • $myvariable 是一个静态属性。使用classname:: 语法分配。
  • static::$instant !== null - 所以如果它是 NOT null 你创建一个新的。如果它是空的,你只返回空?你确定吗?
  • 哦,抱歉 A::initial() 中的代码错误,应该是 if (static::$instant === null)
  • @u_mulder ,我做到了。来自 A::initial() 的瞬间

标签: php class methods static singleton


【解决方案1】:

参考手册:http://php.net/manual/en/language.oop5.static.php

声明为静态的属性不能通过实例化的类对象访问(尽管静态方法可以)。

所以,无论如何,你不能从类实例中设置 static 属性。

作为一个选项,您可以添加一些设置器来设置您的静态变量:

public function setMyVar($value) {
    static::$myvariable = $value;
}

$this->a->setMyVar(true);

【讨论】:

    【解决方案2】:

    您的来电,

    $this->a::$myvariable = true;
    

    PHP 手册说,

    将类属性或方法声明为静态使它们无需实例化即可访问。声明为静态的属性不能被实例化的类对象访问(尽管静态方法可以)。

    这就是您无法通过对象分配静态属性的原因。

    只需这样做:

    A::$myvariable = true;
    

    这是参考:

    【讨论】:

    • 但是,在我的“真实”代码中,我使用命名空间,并且我不会重新导入(在这种情况下)使用“使用”的类
    猜你喜欢
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    相关资源
    最近更新 更多