Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - change class variable/function from outside the class

Can I change a function or a variable defined in a class, from 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()
...
like image 960
Alex Avatar asked Dec 21 '22 18:12

Alex


2 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;
like image 71
Jake N Avatar answered Jan 09 '23 10:01

Jake N


There are several possibilities to achieve your goal. You could write a getMethod and a setMethod in your Class in order to set and get the variable.

class moo{

  public $somestuff = 'abcdefg';

  function setSomestuff (value) {
     $this->somestuff = value;
  }

  function getSomestuff () {
     return $this->somestuff;
  }
}
like image 43
Thariama Avatar answered Jan 09 '23 08:01

Thariama