0

Is it possible to use an include statement that contains conditional statements in a control structure? It's hard to explain, so here's an example:

if (...) { 
} 
elseif (...) { 
} 
elseif (...) {
}
elseif (...) {
}
else {
}

Let's say my third elseif contained a lot of code and I wanted to put it in another file and use an include statement instead. Could I do that? When I tried to, it was giving my an "unexpected T_ELSE" error. So it would be something like this:

if (...) {
}
elseif (...) {
}
elseif (...) {
}
include 'abc.php';
else {
}

Also, I couldn't find many sources on the web that give a breakdown of the legal usage of include (I checked out php.net, too), like if you could put the conditions of a conditional statement in an separate file and use an include statement to call it, or use an include statement in an echo statement. If anyone has some good references, I'd appreciate it. Thank you all in advance.

2
  • 3
    It has to go inside one of the sets of {}, not between it and an else/elseif. Commented Feb 4, 2012 at 4:34
  • iam agree with @Jared Farrish Commented Feb 4, 2012 at 4:35

1 Answer 1

2

Yes, you can do that.

As Jared pointed out, the problem is that the include line isn't within a bracketed block.

However, conditional loading of code in this manner is typically frowned upon. You should only use it for determining what you will load as you need it. I recommend looking into auto-loading what you need, as the standard solution to this problem:

http://php.net/manual/en/language.oop5.autoload.php

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

2 Comments

OK, cool. I wish there were some kind of a list of "you can do this, you can't do that." Short of just trying it out and seeing what happens, you can't always find the answer you need. Thanks for the help.
@Sean, the documentation is exactly what you're looking for. php.net/docs.php When it doubt, experiment.

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.