I have a PHP script that executes another PHP script(that contains quite a lot of functions some being recursive) using the include method , multiple times, but the second time i get a error saying that one of the function in the "included" PHP script can not be redeclared.
Now i get that what include does is just inserting the commands from the referenced script in the script that called it and thus I have like the same functions declare too many times resulting in a abomination.
So, could somebody tell me how i should approach this problem?
This is the included script
<?php
$_SESSION['det']=0;
$x=array();
function valid($k)
{
for($i=1;$i<$k;$i++)
if($GLOBALS['x'][$i]==$GLOBALS['x'][$k])
return 0;
return 1;
}
function semn($k)
{
$nr=0;
for($i=1;$i<$k;$i++)
for($j=$i+1;$j<=$k;$j++)
if($GLOBALS['x'][$i]>$GLOBALS['x'][$j])
$nr++;
if($nr%2==0)
return 1;
else
return -1;
}
function determinant($k)
{
$prod=1;
for($i=0;$i<$k;$i++)
$prod*=$_SESSION['matrix'][$i][$GLOBALS['x'][$i+1]-1];
$_SESSION['det']+=semn($k)*$prod;
}
function solve($k,$n)
{
for($i=1;$i<=$n;$i++)
{
$GLOBALS['x'][$k]=$i;
if(valid($k))
if($k==$n)
{
determinant($k);
}
else
solve($k+1,$n);
}
}
$n=$_SESSION['size'];
solve(1,$n);
unset($x);
?>
And this is the script thats includes.
<?php
include 'determinant.php';
if(!$_SESSION['det'])
{
echo "The inverse cant be calculated cause the determinant is equla to 0.";
}
else
{
$detA=$_SESSION['det'];
//Transpusa
for($i=0;$i<$_SESSION['size']-1;$i++)
for($j=$i+1;$j<$_SESSION['size'];$j++)
{
$aux=$_SESSION['matrix'][$i][$j];
$_SESSION['matrix'][$i][$j]=$_SESSION['matrix'][$j][$i];
$_SESSION['matrix'][$j][$i]=$aux;
}
$Dcar=array();
//Matricile caracteristice
for($i=0;$i<$_SESSION['size'];$i++)
{
for($j=0;$j<$_SESSION['size'];$j++)
{
$r=0;
$c=0;
$semn=1;
$a=array();
$_SESSION['matrix'][$i][$j]
for($m=0;$m<$_SESSION['size'];$m++)
{
if($m==$i)
continue;
else
{
for($n=0;$n<$_SESSION['size'];$n++)
{
if($n==$j)
continue;
else
{
$a[$r][$c]=$_SESSION['matrix'][$m][$n];
$c++;
}
}
$r++;
$c=0;
}
}
//Apelarea functiei determinant pentru fiecare matrice
$aux=$_SESSION['matrix'];
$_SESSION['matrix']=$a;
$_SESSION['size']-=1;
include 'determinant.php';
$_SESSION['matrix']=$aux;
$_SESSION['size']+=1;
$Dcar[$i][$j]=($semn*$_SESSION['det'])/$detA;
$semn*=-1;
}
}
for($i=0;$i<$_SESSION['size'];$i++)
{
for($j=0;$j<$_SESSION['size'];$j++)
echo $Dcar[$i][$j]." ";
echo "<br>";
}
}
?>
Use include_once() function.
Follow documentation:
This is a behavior similar to the include statement, with the only
difference being that if the code from a file has already been
included, it will not be included again. As the name suggests, it will
be included just once.
You can use require_once() instead. It's all in the name in this case ;-)
Related
I know I can use return to exit current script file, but what if we want to exit current script from inside a function?
For example, we define a exitScript() function that prints closing html tags and exits current script file, but if we use return it only exits from current function. Also exit() terminates whole script not only current file.
You can use Exceptions to do this, not particularly elegant, but this should do what your after, replace these methods.
public function fn1()
{
try {
$fn2 = $this->fn2();
}
catch ( Exception $e ) {
}
echo 'I want this to be displayed no matter what!';
}
public function fn4()
{
$random = rand(1, 100);
if ($random > 50)
{
return true;
}
else
{
// I want to exit/break the scirpt to continue running after
// the $fn2 = $this->fn2() call in the $this->fn1() function.
//exit();
throw new Exception();
echo "This shouldn't be displayed.";
}
}
You can return from an included file to the 'main file', skipping execution of the remaing part after the return.
So this will output: ABXend, skipping C
a.php
<?php
echo 'A';
include('b.php');
echo 'end';
?>
and b.php
<?php
echo 'B';
if(!x(6))return; //return here
echo 'C';
function x($num){
echo 'X';
if($num!==1)return false;
}
?>
<?php
function testEnd($x) {
if ( ctype_digit($x) ) {
if ( $x == 24 ) {
return true;
exit;
} else {
return false;
exit;
}
} else {
echo 'If its not a digit, you\'ll see me.';
return false;
exit;
}
}
$a = '2';
if ( testEnd($a) ) {
echo 'This is a digit';
} else {
echo 'No digit found';
}
?>
Is exit needed along with return when using them inside a php function? In this case, if anything evaluated to false, i'd like to end there and exit.
No it's not needed. When you return from a function then any code after that does not execute. if at all it did execute, your could would then stop dead there and not go back to calling function either. That exit should go
According to PHP Manual
If called from within a function, the return statement immediately
ends execution of the current function, and returns its argument as
the value of the function call. return will also end the execution of
an eval() statement or script file.
Whereas, exit, according to PHP Manual
Terminates execution of the script.
So if your exit was really executing, it would stop all the execution right there
EDIT
Just put up a small example to demonstrate what exit does. Let's say you have a function and you want to simply display its return value. Then try this
<?php
function test($i)
{
if($i==5)
{
return "Five";
}
else
{
exit;
}
}
echo "Start<br>";
echo "test(5) response:";
echo test(5);
echo "<br>test(4) response:";
echo test(4);
/*No Code below this line will execute now. You wont see the following `End` message. If you comment this line then you will see end message as well. That is because of the use of exit*/
echo "<br>End<br>";
?>
I have one not understood point In MVC pattern. Please help understood.
for example we have table for cars in database, we want obtain and print results from table, but if results are not found (0 rows), in this case print: "We dont have results"
this is models.php
class modesl {
function getCars () {
$res = $this->db->query("SELECT names FROM cars");
if ($res->num_rows == 0) {
return "We dont have results";
}
else {
return $res;
}
}
}
this is views.php
class views {
function loadHTML ($resultFromCars) {
require 'carspage.php';
}
}
this is carspage.php
<html>
<body>
<?php
if (is_object($resultFromCars)) {
while ($row = $resultFromCars->fetch_assoc()) {
echo $row['names']."<br>";
}
}
else {
echo $resultFromCars;
}
?>
</body>
</html>
this is controllers.php
class controllers {
function generatePage () {
$model = new models();
$resultFromCars = $model->getCars();
$view = new views();
$view->loadHTML($resultFromCars);
}
}
This works, but as I know, many php code in view, (that is condition if (is_object) { } else { } ) is not right MVC. tell please for this concret case, what must be change in my architecture (lol), for obtain right MVC concept?
I like the answer provided by Havelock.
I would adjust this even further, by making sure your model already returns the data in an array format (or false, if nothing is found). Therefore, the logic for extracting data from resultset stays in the model, where it really should be.
Your view becomes even simpler then:
<?php
if (!empty($results)) {
foreach ($results as $row) {
echo $row['name'] . "<br />";
}
} else {
echo "Eh, Nothing found...";
}
You seem to have done a good job, just one small thing to improve. As the model is a wrapper for data only, so you should return only data (and no strings, containing error/exception messages). In the case there's no data to return, then return FALSE, as it's done in PHP.
class CarModel {
function getCars () {
$res = $this->db->query("SELECT names FROM cars");
if ($res->num_rows == 0) {
return FALSE; // if that happens, the function will stop execution here, so no "else" is needed
}
return $res;
}
}
And in your view
<?php
if ($resultFromCars === FALSE && !empty($resultFromCars)) {
echo "We don't have results";
}
else { // now you know it's not FALSE, so it must be an object, no need to check whether it is one
while ($row = $resultFromCars->fetch_assoc()) {
echo $row['names']."<br>";
}
}
?>
Please check this below code. After for loop remaining code is not executing. It suppose to print "Helo", but it is not printing any thing.
for($i=0;$i<10;$i++)
{
$minrate=$obj_iScripts->min_avg_rate($roomnumber[$id_array[$i]], $amount_ary[$id_array[$i]], $totalrooms);
$all_min_price[]=$minrate;
if($_SESSION['star'][$id_array[$i]]>=1 && $_SESSION['star'][$id_array[$i]]<=5)
{
//include 'searchresult_table.php';
}
}
echo "Helo";
code:
public function min_avg_rate($roomnumber,$rates,$totalrooms)
{
$ary_name='iArray';
$total=0;
for($i=1;$i<=$totalrooms;$i++)
{
${$ary_name.$i}=array();
$temp=max($rates);
for($j=0;$j<count($roomnumber);$j++)
{
if($roomnumber[$j]==$i)
{
if($temp>$rates[$j])
$temp=$rates[$j];
${$ary_name.$i}=$temp;
}
}
$total=$total+${$ary_name.$i};
}
return $total/$totalrooms;
}
From what code you have posted -the min_avg_rate() function within your class would seem to be malfunctioning
I have a functions.php page with some functions, it is required in the default.php page which is required by all my other pages (index.php) at the first line.
index.php (1st line after <?php
require("includes/default.php");
default.php
<?php
//mysql
require("templates.php");
require("functions.php");
?>
functions.php
<?php
function rating_format($num) {
if ($num > 0) {
return "+" . $num;
}
elseif ($num < 0) {
return "-" . $num;
}
else {
return $num;
}
}
function thumbnail_url($value) {
if ($value == "") {
return "no_favicon.png";
}
else {
return $value;
}
}
?>
I use both functions defined in functions.php in index.php. However, only the second function seems to be defined. Whenever trying to use the first function, it spits out an function undefined error.
I've rearranged the code several times and don't know what is wrong with it. The function is defined before I even use it.
Any help is appreciated.
Try changing the name of the functions.php file to something more unique / less generic, like rating.fcns.php.
I would start by replacing the includes with the actual code for the time being, just to see if the issue is with your includes or your functions.