Alex Rivera | Logout

In php when initializing a class how would one pass a variable to that class to be used in its functions?

Asked 2009-01-27T18:10:17.253
44

So here is the deal. I want to call a class and pass a value to it so it can be used inside that class in all the various functions ect. ect. How would I go about doing that?

Thanks, Sam

Edit
Report

1 Answer

-1

Wow I cannot believe the answers here! They will all work but are wrong, the right way of set the variables is by a getter and setter, this allows you to set your variable neatly and perform checks etc on them. e.g.

class myClass {

    private $myVar;

    public function set_var($var) {  // You can then perform check on the data etc here
       $this->myVar = $var;
    }

    function __construct() { // PHP5 constructor

    }

    public function do_something() {
        echo "blah";
    } 

}

What this allows you to do is call the object correctly e.g.

$objNew = new myClass();
$objNew->set_var("Set my variable");
$objNew->do_something();

This is the tidy way of doing it and on large projects and scripts you will be glad of this, I am having this problem right now with some-else's script which cannot be updated easily because it has been written in the other ways mentioned in this page.

It also allows you to have an unlimited number of variables for the class with out a silly call to the object e.g.

$objNew = new myClass("var1","var1","var1","var1","var1","var1","var1","var1","var1","var1","var1","var1","var1","var1","var1","var1","var1");

This is basically no clearer than using a function.

answered 2011-02-21T16:37:16.877

Your Answer