4

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()
...
6
  • What do you mean by "include file #1"? Commented Feb 10, 2011 at 9:27
  • $somestuff appears to be a local variable. Can't you just change the value of $what after $what = moo::whatever()? Commented Feb 10, 2011 at 9:27
  • 1
    what do you mean by 'change a function'? Commented Feb 10, 2011 at 9:27
  • Did you mean to write a "meta" programming to change a function ? Commented Feb 10, 2011 at 9:29
  • 1
    Not sure about but possible duplicate of Can I include code into a PHP class? Commented Feb 10, 2011 at 9:31

3 Answers 3

7

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;
Sign up to request clarification or add additional context in comments.

Comments

3

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;
  }
}

Comments

1

Set it as an instance attribute in the constructor, then have the method return whatever value is in the attribute. That way you can change the value on different instances anywhere you can get a reference to them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.