【问题标题】:PHP Create class variablesPHP 创建类变量
【发布时间】:2012-12-28 01:35:56
【问题描述】:

有什么方法可以在方法中创建类静态变量吗? 像这样..

class foo {

    public function bind($name, $value) {
         self::$name = $value;
    }

};

或者是否有其他解决方案可以将变量绑定到类,然后在没有长而丑陋的语法“$this->”的情况下使用它

【问题讨论】:

  • 我觉得 self::$name 比 $this->name 丑多了...
  • 我没有得到你的代码,它有什么作用?
  • 如果你打算绑定未知数量的变量,你可以让你的类实现 ArrayAccess
  • @kennypu 品味问题
  • @non true。我认为 Adam 正在谈论这个:php.net/manual/en/class.arrayaccess.php 就个人而言,如果我有未知变量,我会创建一个名为的类变量,比如说,变量是一个数组,然后 bind 就可以了:$this->variables[ $name] = $value

标签: php variables static


【解决方案1】:

我不确定我是否理解这个问题。但是如果你想在运行时附加变量,你可以这样做:

abstract class RuntimeVariableBinder
{
    protected $__dict__ = array();

    protected function __get($name) {
        if (isset($this->__dict__[$name])) {
            return $this->__dict__[$name];
        } else {
            return null;
        }
    }

    protected function __set($name, $value) {
        $this->__dict__[$name] = $value;
    }
}


class Foo
extends RuntimeVariableBinder
{
    // Explicitly allow calling code to get/set variables
    public function __get($name) {
        return parent::__get($name);
    }
    public function __set($name, $value) {
        parent::__set($name, $value);
    }
}

$foo = new Foo();
$foo->bar = "Hello, world!";
echo $foo->bar; // Prints "Hello, world!"

http://codepad.org/H9bz2uVp

【讨论】:

    【解决方案2】:

    使用self 会导致致命错误,因为该属性未声明。您必须使用$this,然后可以将其作为公共变量进行访问:

    <?php
    class foo { 
        public function bind($name, $value) {
             $this->$name = $value;
        }
    
    }
    
    $foo = new Foo;
    $foo->bind('bar','Hello World');
    
    echo '<pre>';
    print_r($foo);
    echo $foo->bar;
    echo '</pre>';?>
    

    【讨论】:

    • 但在变量是否存在或它的值可能是什么方面完全取决于代码流和程序状态。这使得它足够私密,可用于任何实际用途。
    猜你喜欢
    • 2012-03-21
    • 1970-01-01
    • 2017-04-04
    • 2022-07-31
    • 1970-01-01
    • 2012-09-02
    • 2016-03-19
    • 1970-01-01
    • 2021-05-18
    相关资源
    最近更新 更多