PHP - changing a class variable / function from outside the class

Is it possible to change a function or variable defined in a class outside the class, but without using global variables?

this is the class inside include file # 2:

class moo{ function whatever(){ $somestuff = "...."; return $somestuff; // <- is it possible to change this from "include file #1" } } 

in the main application, this is how the class is used:

 include "file1.php"; include "file2.php"; // <- this is where the class above is defined $what = $moo::whatever() ... 
+4
source share
3 answers

Are you asking about getters and setters or static variables

 class moo{ // Declare class variable public $somestuff = false; // Declare static class variable, this will be the same for all class // instances public static $myStatic = false; // Setter for class variable function setSomething($s) { $this->somestuff = $s; return true; } // Getter for class variable function getSomething($s) { return $this->somestuff; } } moo::$myStatic = "Bar"; $moo = new moo(); $moo->setSomething("Foo"); // This will echo "Foo"; echo $moo->getSomething(); // This will echo "Bar" echo moo::$myStatic; // So will this echo $moo::$myStatic; 
+6
source

There are several possibilities to achieve your goal. You can write getMethod and setMethod in your class to set and get the variable.

 class moo{ public $somestuff = 'abcdefg'; function setSomestuff (value) { $this->somestuff = value; } function getSomestuff () { return $this->somestuff; } } 
+3
source

Set it as an instance attribute in the constructor, then return the method to any of the attributes. Thus, you can change the value in different instances at any place where you can get a link to them.

+1
source

Source: https://habr.com/ru/post/1339152/


All Articles