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
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
In new versions of PHP (5 and up), the function __constuct is called whenever you use "new {Object}", so if you want to pass data into the object, add parameters to the construct function and then call
Named constructors are being phased out of PHP in favor of the __construct method.
This means less maintenance in the long run.
Order of passed variables is not important anymore, (no more writing defaults like 'null': someClass(null, null, true, false))
Adding a new variable is less hassle (don't have to write the assignment in the constructor)
When you look at the instantiation of the class you'll know immediately what the passed in variables relate to:
vs
Think everyone's missing the obvious here. Yes, the PHP4 constructor is deprecated, but you can write your class to be backwards compatible like this:
You can do this like that:
or you can use __construct instead of SomeClass for constructor in php5.
This is how I do mine
Create an instance and then call the function add
11 will be written to the page not a very useful example because you would prefer to pass value to add when you called it but this illustrates the point.
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.
What this allows you to do is call the object correctly e.g.
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.
This is basically no clearer than using a function.