我对OOP PHP缺乏经验,但这是我的问题...假设我有一个带有一个属性的类:
class myClass {
public $property = array();
public function getProperty() {
return $this->property;
}
}
如何在不以任何方式更改类本身的情况下更改 $property 的值,或者通过实例化对象,然后更改其属性。还有其他方法吗?使用范围解析?
希望这是有道理的,任何帮助将不胜感激。
你想要的是一个静态成员
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++;
}
}
然后你像访问它一样
MyClass::$MyStaticMember = "Some value"; //Note you use the $ with the variable name
现在,对于静态成员设置的任何内容,任何实例和所有内容都将看到相同的值,因此例如以下内容
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
我希望这就是你要找的
<?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
?>