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

Viewed 84462

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

7 Answers

I want to call a class and pass a value to it so it can be used inside that class

The concept is called "constructor".

As the other answers point out, you should use the unified constructor syntax (__construct()) as of PHP 5. Here is an example of how this looks like:

class Foo {
    function __construct($init_parameter) {
        $this->some_parameter = $init_parameter;
    }
}

// in code:

$foo = new Foo("some init value");

Notice - There are so-called old style constructors that you might run into in legacy code. They look like this:

class Foo {
    function Foo($init_parameter) {
        $this->some_parameter = $init_parameter;
    }
}

This form is officially deprecated as of PHP 7 and you should no longer use it for new code.

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

$obj = new Object($some, $parameters);

class Object {
    function __construct($one, $two) {}
}

Named constructors are being phased out of PHP in favor of the __construct method.

You can do this like that:

class SomeClass
{
   var $someVar;
   function SomeClass($yourValue)
   {
       $this->someVar = $yourValue;
   }

   function SomeFunction()
   {
       return 2 * $this->someVar;
   }
}

or you can use __construct instead of SomeClass for constructor in php5.

Related