0

I have this array:

$methodsOutput = array("MidUpperArmMuscleArea","ArmSpan_HeightEstimation","BMIBeforePregnancy",
                "PregnancyTotalWeightGain","PregnancyWeeklyWeightGain","MS_CurrentBMI_BMIPregnancyWeeks",
                "PregnancyDueDate","PregnancyWeeks","WeightEstimation","WHO_BMI_2000_IdealBMI",
                "WHO_BMI_2000_IdealWeight","WHO_HeightAge_2006_IdealHeight","WHO_WeightAge_2006_IdealWeight");

and for each one I have the respective class (all included in file).

How can I instantiate dynamically this.

I try this:

foreach($methodsOutput as $method) {
    $$method= new $method();
}

but get:

Fatal error: Class 'MidUpperArmMuscleArea' not found in...

7
  • 1
    Do NOT use variable variables. Your code becomes an unmaintainable impossible-to-debug mess. Commented Mar 22, 2012 at 17:15
  • if you get Class '...' not found then the class is not found. No way around it. If you think the class should be found, then test your assumption to be correct. Commented Mar 22, 2012 at 17:20
  • @Munir: which is why it's a comment. Commented Mar 22, 2012 at 17:21
  • @MarcB: thx. I did not want to be rude Commented Mar 22, 2012 at 17:23
  • @Yoshi: If I comment the 'foreach' code and put $instance = new MidUpperArmMuscleArea() works. Commented Mar 22, 2012 at 17:25

2 Answers 2

1

Objectively, this looks like a really bad way of doing this..

Anyway, that's not what you want to hear.

The class 'MidUpperArmMuscleArea' must really not exist in that context, as your syntax is correct. Since you mention all these classes are in the same file, are you defining them after you are executing this code?

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry all! I am new here and I forgot to check the tag 'Symfony2' in the question. The array should be: $methodsOutput = array("MyProject\MyBundle\Entity\MidUpperArmMuscleArea","MyProject\MyBundle\Entity\ArmSpan_HeightEstimation",...); and now works! but I change this... I will pass this variables in YML file. Thx all! and sorry again.
0

Do you have that class "MidUpperArmMuscleArea" ? You could to use class_exists to test.

1 Comment

Realy. The class is 'MyProject\MyBundle\Entity\MidUpperArmMuscleArea'. Cause I am using Symfony2. Thx!

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.