如何破坏代码而不使用if else?
请看下面的代码:
// this is a.php
if(file_exists('overrides/a.php')){
require('overrides/a.php');
}
// many codes bellow
// if there is ''overrides/a.php', the codes bellow will not excute.
// but I don't what to use if(){}else{} to do it which like bellow codes
if(file_exists('overrides/a.php')){
require('overrides/a.php');
}else{
// original codes
}
// I want to do it like
if(file_exists('overrides/a.php')){
require('overrides/a.php');
// some codes here to break all codes after this in this php
}
// original codes
// notice:
// if there is another all.php
require('a.php');
require('b.php'); // can not break b.php when break a.php
all.php
<?php
require('a.php');
echo 'hello';
a.php只会
<?php
echo 'kkk<br>';
exit();
echo '222';
将显示:
kkk
not kkk hello
答案 0 :(得分:1)
all.php
<?php
require('a.php');
echo 'hello';
?>
a.php只会
<?php
echo 'kkk<br>';
return;
echo '222';
?>
将给出
kkk
hello
答案 1 :(得分:0)
您可以使用三元运算符而不是if else,如下所示:
(条件)? statements1:语句2;
如果condition为true,则执行statement1,否则将执行statement2。
在您的情况下,您可以替换
if(file_exists('overrides/a.php')){
require('overrides/a.php');
}else{
// original codes
}
通过
(file_exists('overrides/a.php'))? require('overrides/a.php'):// original codes ;
答案 2 :(得分:0)
而不是:
if(file_exists('overrides/a.php')){
require('overrides/a.php');
}
使用:
include('overrides/a.php');
如果文件丢失,它会发出警告而不是错误。您可以设置php以显示这些警告。