所以这里是交易.我想调用一个类并将值传递给它,以便它可以在所有各种函数中的类中使用.等.我该怎么做呢?
谢谢,山姆
我想调用一个类并将值传递给它,以便可以在该类中使用它
这个概念被称为"构造函数".
正如其他答案所指出的那样,您应该使用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开始,此表单已正式弃用,您不应再将其用于新代码.
在新版本的PHP(5及更高版本)中,每当使用"new {Object}"时都会调用函数__constuct,因此如果要将数据传递给对象,请将参数添加到构造函数中,然后调用
$obj = new Object($some, $parameters); class Object { function __construct($one, $two) {} }
命名构造函数正逐步退出PHP,转而使用__construct方法.
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))
这就是我的做法
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将写入页面不是一个非常有用的例子,因为你更喜欢在调用时传递值来添加,但这说明了这一点.