我需要在基于数据的函数中声明一堆变量,该数据通过使用foreach
与switch
语句与另一个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语句的变量范围(在这里,在这里,在这里和在这里,并试图找到更多),但是没有人知道为什么$data_def_id
,在函数设置为0
的开始时,不会被重置为内部foreach
中的任何值。我尽量避免使用global
变量,因为其中一些功能将在产品中使用。
我需要能够在整个私有函数(包括foreach
, switch
等)中使用private function
中的变量。我做错了什么?我该如何改正?
Ok找到答案了。
class Users {
public function createUserData(){
$user = $this->getUserData(); //not shown function
$this->createFullDataSet($user);
}
private function createFullDataSet($user){//variables required later
static $entity_def_id = 0; //static within function instead of non-static within foreach
static $entity_id = 0;
static $data_def_id = 0;
static $user_id = 0;
//thats plenty, you get the idea
foreach( $user['meta'][0] as $key => $value) {
//remainder of that method with switch( foreach () )
}
}
private function createRelation( $data_def_id ){
// something awesome happens!
}
}
通过在函数内将变量声明为static
,整个函数,包括函数内的方法都可以使用这些变量。花了我很长时间。
将它们定义为class properties
如何?
class User {
private $data_def_id;
private function createFullDataSet($user){
//....
$this->data_def_id = $this->createDataDef( some $vars );
}
}