简体   繁体   中英

Is it possible to change a property of a class outside of the class? (PHP)

I'm quite inexperienced with OOP PHP but here's my question...let's say I have this class with one property:

class myClass {

    public $property = array();

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

}

How would it be possible to change the value of $property without altering the class itself in any way, or by instantiating an object out of it, then changing its property. Is there any other way of doing it? Using scope resolution?

Hope that makes sense, any help would be much appreciated.

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

I hope this is what you are looking for

<?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

EDIT :

As others said , yes you need the variable to be declared as static (if you want to modify the variable without creating new instance of the class or extending it)

<?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
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM