在PHP初始化类时,如何将变量传递给该类以在其函数中使用?

38 php variables class

所以这里是交易.我想调用一个类并将值传递给它,以便它可以在所有各种函数中的类中使用.等.我该怎么做呢?

谢谢,山姆

Tom*_*lak 59

我想调用一个类并将值传递给它,以便可以在该类中使用它

这个概念被称为"构造函数".

正如其他答案所指出的那样,您应该使用PHP 5中的统一构造函数语法(__construct()).以下是一个示例:

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

// in code:

$foo = new Foo("some init value");
Run Code Online (Sandbox Code Playgroud)

注意 - 您可能会在遗留代码中遇到所谓的旧样式构造函数.它们看起来像这样:

class Foo {
    function Foo($init_parameter) {
        $this->some_parameter = $init_parameter;
    }
}
Run Code Online (Sandbox Code Playgroud)

从PHP 7开始,此表单已正式弃用,您不应再将其用于新代码.

  • 您可能应该调用方法__construct()而不是Foo,因为这是PHP5中推荐的行为 (13认同)
  • -1,因为你应该使用__construct(),请参阅@CiaranMcNulty的帖子 (2认同)
  • @Faizan` $ foo = new Foo($ name);`当然. (2认同)

dav*_*gr8 34

在新版本的PHP(5及更高版本)中,每当使用"new {Object}"时都会调用函数__constuct,因此如果要将数据传递给对象,请将参数添加到构造函数中,然后调用

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

class Object {
    function __construct($one, $two) {}
}
Run Code Online (Sandbox Code Playgroud)

命名构造函数正逐步退出PHP,转而使用__construct方法.


小智 22

class SomeClass
{
    public $someVar;
    public $otherVar;

    public function __construct()
    {
        $arguments = func_get_args();

        if(!empty($arguments))
            foreach($arguments[0] as $key => $property)
                if(property_exists($this, $key))
                    $this->{$key} = $property;
    }
}

$someClass = new SomeClass(array('someVar' => 'blah', 'otherVar' => 'blahblah'));
print $someClass->someVar;
Run Code Online (Sandbox Code Playgroud)

从长远来看,这意味着更少的维护.

传递的变量的顺序不再重要,(不再写'null'的默认值:someClass(null,null,true,false))

添加新变量不那么麻烦(不必在构造函数中编写赋值)

当你查看类的实例化时,你会立即知道传入的变量与什么相关:

Person(null, null, true, false) 
Run Code Online (Sandbox Code Playgroud)

VS

Person(array('isFat' => true, 'canRunFast' => false)) 
Run Code Online (Sandbox Code Playgroud)


and*_*rew 12

这就是我的做法

class MyClass {

       public variable;  //just declaring my variables first (becomes 5)
       public variable2; //the constructor will assign values to these(becomes 6)

       function __construct($x, $y) {
            $this->variable  = $x;
            $this->variable2 = $y;
       }

       function add() {
            $sum = $this->variable + $this->variable2
            return $sum;
       }

} //end of MyClass class
Run Code Online (Sandbox Code Playgroud)

创建一个实例,然后调用函数add

$myob = new MyClass(5, 6); //pass value to the construct function
echo $myob->add();
Run Code Online (Sandbox Code Playgroud)

11将写入页面不是一个非常有用的例子,因为你更喜欢在调用时传递值来添加,但这说明了这一点.

  • 不应该是`public $ variable`&`public $ variable2`而不是? (5认同)