Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/248.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP,为类内的类实例设置静态变量时出错_Php_Class_Methods_Static_Singleton - Fatal编程技术网

PHP,为类内的类实例设置静态变量时出错

PHP,为类内的类实例设置静态变量时出错,php,class,methods,static,singleton,Php,Class,Methods,Static,Singleton,我正在尝试在另一个类中调用类方法 <?php class A { public static $instant = null; public static $myvariable = false; private function __construct() {} public static function initial() { if (static::$instant === null) { $self =

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

<?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);
我该怎么办? 发生了什么事? 我错了吗

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

抱歉,英语不好。

请参阅手册:

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

因此,无论如何,您不能从类实例中设置
静态
属性

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

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

$this->a->setMyVar(true);
你的电话

$this->a::$myvariable = true;
PHP手册上说

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

这就是无法通过对象指定静态属性的原因

只需这样做:

A::$myvariable = true;
以下是参考资料:


这是非常不寻常的代码,我认为这里有几个问题让您和其他可能的回答者感到困惑。尝试将其放入
B
构造()
方法中,您会立即看到几个问题之一:
var\u dump($a\u实例)
我得到了
NULL
打印输出,因此您的代码不会执行您认为它会执行的操作。
$myvariable
是一个静态属性。使用
类名::
语法和
静态::$instant!==null
-因此,如果它不是null,则创建一个新的。如果它是null,你就返回null?你确定吗?哦,对不起,A::initial()中的错误代码应该是if(static::$instant==null)@u_mulder,是的。来自A::initial()的instantce,但在我的“real”代码中,我使用名称空间,并且不会使用“use”重新导入(在本例中)类
$this->a::$myvariable = true;
A::$myvariable = true;