In php when initializing a class how would one pas

2019-01-30 14:36发布

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条回答
放荡不羁爱自由
2楼-- · 2019-01-30 15:29

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.

查看更多
登录 后发表回答