1

我对 OOP PHP 非常缺乏经验,但这是我的问题……假设我有一个具有一个属性的类:

class myClass {

    public $property = array();

    public function getProperty() {
        return $this->property;
    }

}

如何在不以任何方式更改类本身的情况下更改 $property 的值,或者通过实例化一个对象,然后更改其属性。还有其他方法吗?使用范围解析?

希望这是有道理的,任何帮助将不胜感激。

4

2 回答 2

6

What you want is a static member

class MyClass {
   public static $MyStaticMember = 0;

   public function echoStaticMember() {
      echo MyClass::$MyStaticMember;
      //note you can use self instead of the class name when inside the class
      echo self::$MyStaticMember;
   }

   public function incrementStaticMember() {
      self::$MyStaticMember++;
   }
}

then you access it like

MyClass::$MyStaticMember = "Some value"; //Note you use the $ with the variable name

Now any instances and everything will see the same value for whatever the static member is set to so take for instance the following

function SomeMethodInAFarFarAwayScript() {
   echo MyClass::$MyStaticMember;
} 

...

MyClass::$MyStaticMember++; //$MyStaticMember now is: 1

$firstClassInstance = new MyClass();

echo MyClass::$MyStaticMember; //will echo: 1
$firstClassInstance->echoStaticMember(); //will echo: 1

$secondInstance = new MyClass();
$secondInstance->incrementStaticMember(); // $MyStaticMember will now be: 2

echo MyClass::$MyStaticMember; //will echo: 2
$firstClassInstance->echoStaticMember(); //will echo: 2
$secondInstance->echoStaticMember(); //will echo: 2

SomeMethodInAFarFarAwayScript(); //will echo: 2

PHPFiddle

于 2013-10-06T02:48:39.560 回答
2

我希望这就是你要找的

<?php

class myClass {

    public $property = array();

    public function getProperty() {
        print_r($this->property);
    }

}


$a = new myClass();
$x = array(10,20);

$a->property=$x; //Setting the value of $x array to $property var on public class
$a->getProperty(); // Prints the array 10,20

编辑 :

正如其他人所说,是的,您需要将变量声明为static(如果您想修改变量而不创建类的新实例或扩展它)

<?php
class MyClass {
    public static $var = 'A Parent Val';

    public function dispData()
    {
        echo $this->var;
    }
}

echo MyClass::$var;//A Parent Val
MyClass::$var="Replaced new var";
echo MyClass::$var;//Replacced new var
?>
于 2013-10-06T02:37:37.077 回答