是否可以在课堂外更改课程的属性? (PHP)

时间:2013-10-06 02:32:56

标签: php oop properties

我对OOP PHP缺乏经验,但这是我的问题...让我说这个课有一个属性:

class myClass {

    public $property = array();

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

}

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

希望有意义,任何帮助都会非常感激。

2 个答案:

答案 0 :(得分:5)

你想要的是一个静态成员

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

答案 1 :(得分: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
?>