我怎样才能只为第一个函数调用做些什么?

How can I do something only for the first function call?

我正在使用以下代码从数组中丢失数据:

private function addIndexKey($parent) {
$myKeys = array();
foreach ($parent->children as $child) {
    $pos = $child->varGet('flow_pos');
    if (!isset($pos))
        $pos = $child->position;
    if (isset($child->index))
        $myKeys["$pos"] = $child->index;
    if (isset($child->children) && count($child->children)>0) {
        $subkeys = $this->addIndexKey($child);
        if (count($subkeys)>0)
            $myKeys["$pos"] = $subkeys;
    }
}
ksort($myKeys);
return $myKeys;
}

我正在遍历一个数组数组,当我 return $myKeys 数组时有时会丢失数据。

我假设它是因为在第三种情况下再次调用相同的函数时重新定义了 $myKeys 数组。我希望函数的第一行在第一次调用时只执行一次

有什么办法可以做到吗?

$count = 0;
private function addIndexKey($parent) {
global $count;
if(count == 0)
    $myKeys = array();
$count++
...
}

您可以在您的函数 运行 第一次使用时将变量设置为假,然后在您的函数内部检查是否为真,然后 运行 您的第一行。

$isFirstTime = true;

function Your_function_name(){
global $isFirstTime;
if ($isFirstTime){
//Run some code 
}

$isFirstTime = false;
}

您可以使用不同的方式将其归档。我将在这里展示一些:

  1. 静态变量

    让你的数组静态化,这样初始化只在第一次函数调用时完成,例如

    function addIndexKey($parent) {
    static $myKeys = array();  //Will only be initialized once
    //...
    }
    
  2. 可选参数

    使您的参数可选,并且不要在第一次函数调用时传递数组,例如

    function addIndexKey($parent, $myKeys  = []) {
    //Now call the function like this: addIndexKey($parent, $myKeys)
    }
    addIndexKey($parent)//First call without the optional argument, which means it gets initialized
    
  3. (Class 属性)

    因为您可以看到您的函数,所以我假设您在 class 中,这意味着您可以将 $myKeys 用作 class 属性,这您可以使用空数组进行初始化,例如

    class XY {
      protected $myKeys = [];
    
      private function addIndexKey($parent) {
          //Use '$this->myKeys' here
      }     
    }

根据您之前对代码执行的操作,在函数的第一行检查 $myKeys 是否已创建或者它是否为数组。

if( !is_array($myKeys) )$myKeys = array();
 //OR EITHER
if( !isset($myKeys) )$myKeys = array();