我需要在基于数据的函数中声明一堆变量,这些数据通过使用foreach
withswitch
语句与 another循环foreach
。我想我误解了我正在使用的变量的范围,任何帮助都会很棒。
class Users {
public function createUserData(){
$user = $this->getUserData(); //not shown function
$this->createFullDataSet($user);
}
private function createFullDataSet($user){
foreach( $user['meta'][0] as $key => $value) {
//variables required later
$entity_def_id = 0;
$entity_id = 0;
$data_def_id = 0;
$user_id = 0;
//thats plenty, you get the idea
switch( $key ){
case "id":
//set $user_id to use later
$user_id = $value; // <<-- DOESN'T WORK, only works within the case
break;
case "email":
case "username":
case //lots of other cases...
break;
case "location":
case "hometown":
case "something":
//for the last three, the data structure is the same, good test case
//foreach starts when certain conditions met, irrelevant for question
foreach( $value as $data_key => $data_value ){
$data_type = 'string';
if( is_numeric( $data_value )
$data_type = 'integer';
$data_def_id = $this->createDataDef( some $vars ); //returns an ID using $pdo->lastInsertId(); ( works as has echo'd correctly, at least within this case )
$this->createSomethingElse //with variables within this foreach, works
}
break;
} //end of switch
$this->createRelation( $data_def_id ); // <<-- DOESN'T WORK!! Empty variable
}
}
private function createRelation( $data_def_id ){
// something awesome happens!
}
}
从上面的代码可以看出,我想在switch语句之外使用一个变量,虽然由于现有数据结构需要在foreach
-> switch
->中声明foreach
(这个数据结构很痛苦,这就是为什么需要在任何人问之前完成:不,不能“只是改变以使其更容易”)。
现在我一直在阅读 foreach 和 switch 语句的变量范围(here、here、here和here并试图找到更多),但是对于为什么$data_def_id
在函数的开头设置为 的0
, 没有更明智不要重置为内部出现的任何值foreach
。我试图避免使用global
变量,因为其中一些功能将在产品中使用。
我需要能够在private function
整个私有函数(包括foreach
,switch
等)中使用 , 中的变量。我做错了什么,我该如何解决?