当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《在PHP初始化类时,如何将变量传递给该类以在其函数中使用?》经验,为你挑选了4个好方法。

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

谢谢,山姆



1> Tomalak..:

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

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

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

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

// in code:

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

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

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

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


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

2> davethegr8..:

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

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

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

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



3> 小智..:
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;

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

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

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

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

Person(null, null, true, false) 

VS

Person(array('isFat' => true, 'canRunFast' => false)) 



4> andrew..:

这就是我的做法

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

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

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

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


不应该是`public $ variable`&`public $ variable2`而不是?
推荐阅读
mobiledu2402851373
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有