0

I'm refactoring all the codes given to me and I saw in the code that the're so many repeated variables that is using with other methods

which is this

$tag_id = json_decode($_POST['tag_id']);
    $tag_name = json_decode($_POST['tag_name']);
    $pname = json_decode($_POST['pname']);
    $icode = json_decode($_POST['icode']);
    $bname = json_decode($_POST['bname']);
    $client = json_decode($_POST['client']);
    $package = json_decode($_POST['package']);
    $reference = json_decode($_POST['reference']);
    $prodcat = json_decode($_POST['prodcat']);
    $physical_array = json_decode($_POST['physical_array']);
    $chemical_array = json_decode($_POST['chemical_array']);
    $physpec_array = json_decode($_POST['physpec_array']);
    $micro_array = json_decode($_POST['micro_array']);
    $microspec_array = json_decode($_POST['microspec_array']);
    $prod_type = json_decode($_POST['prod_type']);
    $create_physical_id_array = json_decode($_POST['create_physical_id_array']);
    $create_chemical_id_array = json_decode($_POST['create_chemical_id_array']);
    $create_micro_id_array = json_decode($_POST['create_micro_id_array']);

my question is how can i just use put it in one method and i'll just call it to other methods instead of repeating that code.

thank you

4 Answers 4

1

You can't call it from other methods. Because the variables defined to that method are local. Instead you can define the variables as member variables of that class and access from any method or even from outside class depending upon the access specifier.

 protected $a=2;
 public function method1()
 {
   echo $this->a;
 }
 public function method2()
 {
   echo $this->a;
 }
Sign up to request clarification or add additional context in comments.

Comments

1

Put it in an array

$post_array = [];

foreach($_POST as $key => $value)
{
    $post_array[$key] = json_decode($value);
}
return $post_array;

and then call it like this

$post_array['create_micro_id_array'];

Comments

0

Since it appears you are very much aware of the variable names you want to use... I'll suggest PHP Variable variables To do this, you can loop through your $_POST and process the value while using the key as variable name.

foreach($_POST as $key => $value)
{
    $$key = json_decode($value);
}

At the end of the day, these 4 lines would generate all that... However i'm not so sure of how friendly it may appear to someone else looking at the code. Give it a shot.

Comments

0

You may try extract function.

extract($_POST);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.