我有一个方法,在PHP中只需要执行一次,但会被调用两次。我如何构建这个?
我在PHP中有一个方法,它调用SOAP服务,解析一些数据并返回它 它将返回相同的数据-它询问一个数据对象中有多少条记录 我需要用通行证打两次电话 我的问题是,什么是用PHP构建这个的最佳实践?我试着查看函数是否已经被调用。我是否使用静态变量/函数我有一个方法,在PHP中只需要执行一次,但会被调用两次。我如何构建这个?,php,Php,我在PHP中有一个方法,它调用SOAP服务,解析一些数据并返回它 它将返回相同的数据-它询问一个数据对象中有多少条记录 我需要用通行证打两次电话 我的问题是,什么是用PHP构建这个的最佳实践?我试着查看函数是否已经被调用。我是否使用静态变量/函数 function MinimumRequired() { return $this->NumberPeopleJoined(); } function NumberPeopleJoined () {
function MinimumRequired() {
return $this->NumberPeopleJoined();
}
function NumberPeopleJoined () {
if (isset($NumberPeople)) {
Debug::Show($NumberPeople);
}
static $NumberPeople;
$NumberPeople = Surge_Controller::NumberPeopleJoined();
return $NumberPeople;
}
谢谢 最简单的方法是使用一个全局变量,检查是否为“true”,并在函数末尾将其设置为true。该值也可以缓存 但如果您想让代码变得有趣,可以使用下划线:
http://brianhaveri.github.com/Underscore.php/#memoize只需创建一个本地类成员,并检查该成员是否有值。如果未设置,则将该值设置为从喘振控制器检索到的任何值,如果已设置,则仅返回该值:
<?php
class Surge_Controller {
static public function NumberPeopleJoined() {
echo "Surge_Controller::NumberPeopleJoined() got called.\n";
return 2;
}
}
class Foo {
protected $cacheNumberPeople;
function MinimumRequired() {
return $this->NumberPeopleJoined();
}
function NumberPeopleJoined () {
if( !isset( $this->cacheNumberPeople ) ) {
$this->cacheNumberPeople = Surge_Controller::NumberPeopleJoined();
}
return $this->cacheNumberPeople;
}
}
$foo = new Foo( );
echo $foo->numberPeopleJoined( ) . "\n";
echo $foo->numberPeopleJoined( ) . "\n";
$ php foo.php
Surge_Controller::NumberPeopleJoined() got called.
2
2