When initializing a class how would one pass a variable to that class to be used in its functions in PHP Server Side Scripting Language?



Report

1 Answer(s) available

4 


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.



Report

Related Questions