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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/484537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:53:23  来源:igfitidea点击:

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

phpvariablesclass

提问by Tomalak

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

谢谢,山姆

回答by Tomalak

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:

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

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.

自 PHP 7 起,此表单已正式弃用,您不应再将其用于新代码。

回答by davethegr8

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

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

$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.

PHP 正在逐步淘汰命名构造函数,取而代之的是 __construct 方法。

回答by M.B

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;

This means less maintenance in the long run.

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

Order of passed variables is not important anymore, (no more writing defaults like 'null': someClass(null, null, true, false))

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

Adding a new variable is less hassle (don't have to write the assignment in the constructor)

添加新变量更省事(不必在构造函数中编写赋值)

When you look at the instantiation of the class you'll know immediately what the passed in variables relate to:

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

Person(null, null, true, false) 

vs

对比

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

回答by andrew

This is how I do mine

这就是我的做法

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

Create an instance and then call the function add

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

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

11 will be written to the page not a very useful example because you would prefer to pass value to add when you called it but this illustrates the point.

11 将被写入页面不是一个非常有用的示例,因为您更愿意在调用它时传递值来添加,但这说明了这一点。

回答by empi

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.

或者你可以在 php5 中使用 __construct 而不是 SomeClass 作为构造函数。

回答by Chris Cox

Think everyone's missing the obvious here. Yes, the PHP4 constructor is deprecated, but you can write your class to be backwards compatible like this:

认为每个人都在这里错过了显而易见的事情。是的,PHP4 构造函数已被弃用,但您可以将类编写为向后兼容,如下所示:

class myClass {

    var $myVar;

    function myClass { // PHP4 constructor, calls PHP5 constructor
        $this->__construct();
    }

    function __construct() { // PHP5 constructor
        doSomeStuff($myVar);
    }
}

回答by Chris

Wow I cannot believe the answers here! They will all work but are wrong, the right way of set the variables is by a getter and setter, this allows you to set your variable neatly and perform checks etc on them. e.g.

哇,我简直不敢相信这里的答案!它们都可以工作但都是错误的,设置变量的正确方法是通过 getter 和 setter,这允许您整齐地设置变量并对它们执行检查等。例如

class myClass {

    private $myVar;

    public function set_var($var) {  // You can then perform check on the data etc here
       $this->myVar = $var;
    }

    function __construct() { // PHP5 constructor

    }

    public function do_something() {
        echo "blah";
    } 

}

What this allows you to do is call the object correctly e.g.

这允许您做的是正确调用对象,例如

$objNew = new myClass();
$objNew->set_var("Set my variable");
$objNew->do_something();

This is the tidy way of doing it and on large projects and scripts you will be glad of this, I am having this problem right now with some-else's script which cannot be updated easily because it has been written in the other ways mentioned in this page.

这是这样做的整洁方式,在大型项目和脚本中,您会对此感到高兴,我现在遇到了一些其他脚本的问题,该脚本无法轻松更新,因为它是用本文提到的其他方式编写的页。

It also allows you to have an unlimited number of variables for the class with out a silly call to the object e.g.

它还允许您为类拥有无限数量的变量,而无需对对象进行愚蠢的调用,例如

$objNew = new myClass("var1","var1","var1","var1","var1","var1","var1","var1","var1","var1","var1","var1","var1","var1","var1","var1","var1");

This is basically no clearer than using a function.

这基本上不比使用函数更清楚。