How Can I use a function multiple times on the same page? - php

Say this piece of code:
<?php while($user=mysqli_fetch_array($resultuser)){ ?>
<?php
function my_function($variable) {
//do something here...
}
?>
<?php };?>
This will obviously return this error
Cannot redeclare my_function() previously declared
So what if someone needs to use the same function multiple times across the same page? Is there a way to generate random function() names? Any idea how to get around this? Thanks.
EDIT WITH ACTUAL CODE
<?php while($deposit26=mysqli_fetch_array($resultdeposit26)){ ?>
<td data-th="Hours">
<?php
$week1hours = $deposit26['hours_worked'];
$week2hours = $deposit26['hours_worked_wk2'];
function time_to_decimal($time) {
$timeArr = explode(':', $time);
$decTime = ($timeArr[0] + ($timeArr[1]/60) + ($timeArr[2]/3600));
return $decTime;
}
$groupd26hours = time_to_decimal($week1hours) + time_to_decimal($week2hours);
echo round($groupd26hours, 2);
?>
</td>
<?php };?>

<?php
// Earlier in the file or included with include or require
function time_to_decimal($time) {
$timeArr = explode(':', $time);
$decTime = ($timeArr[0] + ($timeArr[1]/60) + ($timeArr[2]/3600));
return $decTime;
} ?>
...
<?php while($deposit26=mysqli_fetch_array($resultdeposit26)) : ?>
<td data-th="Hours">
<?php
$week1hours = $deposit26['hours_worked'];
$week2hours = $deposit26['hours_worked_wk2'];
$groupd26hours = time_to_decimal($week1hours) + time_to_decimal($week2hours);
echo round($groupd26hours, 2); ?>
</td>
<?php endwhile ?>

you want to declare the function outside the loop and call it inside
<?php
function my_function($variable) {
//do something here...
}
while($user=mysqli_fetch_array($resultuser)){
my_function($variable);
}?>

Let me try and explain what I think could help. I think a good starting point would be to look into including a script or including a script once in your files that require your function logic. That way multiple files can take advantage of the same logic without it having to be repeated. For example:
<?php
// File functions.php
function my_function($variable) {
...
}
?>
<?php
// File one
include_once "functions.php"
...
// Use my_function() from file one
my_function($var);
?>
<?php
// File two
include_once "functions.php"
...
// Use my_function() from file two
my_function($var);
?>

Related

send function's data to a variable

hello i have variable and a function. function get me current logged in user's full name and that works property with this code:
<?PHP
require_once("./include/membersite_config.php");
if(!$fgmembersite->CheckLogin())
{
$fgmembersite->RedirectToURL("login.php");
exit;
}
?>
Welcome back <?= $fgmembersite->UserFullName(); ?>!
now if i want to put function to a variable what i can do?
<?php
$job1 =' ?><?= $fgmembersite->UserFullName();' ?>
<?php
echo "$job1";
?>
and my function is this:
function UserFullName()
{
return isset($_SESSION['name_of_user'])?$_SESSION['name_of_user']:'';
}
the result is just: ?>UserFullName();
<?php
$job1 = $fgmembersite->UserFullName();
?>
What did you tried is assign string value to a variable job
<?php
// <--- maybe lots of other code here --->
$job1 = $fgmembersite->UserFullName();
// <--- maybe lots of other code here --->
?>

Get content of another PHP-File and use variables for current PHP-File

I want to use a variable inside an HTML-String of another PHP-File template.php in my PHP-File constructor.php.
I´m searched on Stackoverflow for a workaround to include the content of the other PHP-File. I included the following code into constructor.php because its known to be more safe instead of using file_get_contents(); Source:
function requireToVar($file){
ob_start();
require($file);
return ob_get_clean();
}
The rest of constructor.php looks like this:
...
$sqli = mysqli_query($mysqli, "SELECT ...");
if(mysqli_num_rows($sqli) > 0){
$ii = 0;
while ($row = $sqli->fetch_assoc()) {
$ii++;
if($row['dummy']=="Example"){
$content.=requireToVar('template.php');
...
The template.php looks like this:
<?php echo "
<div class='image-wrapper' id='dt-".$row['id']."' style='display: none;'>
...
</div>
"; ?>
The constructor.php doesn´t recognize the var $row['id'] inside the string of template.php as its own variable and also doesn´t execute it. The variable definitely works for the other code in constructor.php.
If I´m copy&paste the code of template.php into constructor.php after $content.= its working like a charm. But I want to restructure my constructor.php because its getting to big and this way its easier to customize.
I don´t know how to describe this problem more exactly, but I´m hoping this title fits to my problem.
Update your function
function requireToVar($file,$row_id){
ob_start();
require($file);
return ob_get_clean();
}
so you can call it like that
while ($row = $sqli->fetch_assoc()) {
$ii++;
if($row['dummy']=="Example"){
$content.=requireToVar('template.php',$row['id']);
and display it in template.php like that
<div class="image-wrapper" id="dt-<?php echo $row_id; ?>" style="display: none;"></div>
Use MVC model and renderer functions. For example: index.php
<!DOCTYPE HTML>
<html>
<head>
<title><?=$title; ?></title>
</head>
<body>
<h3><?=$text; ?></h3>
</body>
</html>
Than I'll have PHP array that contains those variables:
$array = array("title"=>"Mypage", "text"=>"Mytext");
Now we will use both in renderer function
function renderer($path, $array)
{
extract($array); // extract function turn keys into variables
include_once("$path.php");
}
renderer("index", $array);
Your approach is rather strange, but anyway; you can access $row from within $GLOBALS array.
Write your template as:
<?php echo "
<div class='image-wrapper' id='dt-".$GLOBALS['row']['id']."' style='display: none;'>
...
</div>
";
?>

Codeigniter vars inside a view functions

I've a function inside a view (I've nested code so there is no alternative).
My problem is made because i want to add some vars inside the function.
I can't access to the var inside the function.
<div>
<?php _list($data); ?>
</div>
<?php
echo $pre; // Perfect, it works
function _list($data) {
global $pre;
foreach ($data as $row) {
echo $pre." ".$row['title']; // output ' title' without $pre var
if (isset($row['childrens']) && is_array($row['childrens'])) _list($row['childrens']);
}
}
?>
Simple... just define the function like this:
function _list($data, $pre=NULL)
then inside the function, you could check if the $pre is NULL then search for it somewhere else... using the global statement in functions is not desirable.
On the other hand you can define('pre',$pre); and use the pre constant created in your function... again not desirable but it would work for your example.
Later edit: DEFINE YOUR FUNCTIONS IN HELPERS
i am not sure why i forgot to suggest that in the first place
define function in view is weird. using global variable make it worse.
maybe you should avoid the global function with this:
<div>
<?php
foreach($data as $row){
_list($pre, $row);
}
?>
</div>
<?php
function _list($pre, $row) {
echo $pre." ".$row['title'];
if (isset($row['childrens']) && is_array($row['childrens'])){
foreach($row['childrens'] as $child){
_list($pre, $child);
}
}
}
?>
btw, define function in helpers would be better
http://ellislab.com/codeigniter/user-guide/general/helpers.html
whsh they help

PHP passing variables into a function

This is really basic PHP. Can someone tell me why this does not work and what I need to do to make it work.
<?php
$test_var=12;
proc_scrn($test_var);
proc_scrn($local_pid)
{
echo "tp12",$local_pid ;
}
?>
Well, you haven't actually created a function there. This would work:
<?php
$test_var=12;
proc_scrn($test_var);
function proc_scrn($local_pid='')
{
echo "tp12: ".$local_pid;
}
?>
function proc_scrn($local_pid)
{
// something
}
PHP- User-defined functions
Pretty simple
<?php
$var=1;
function proc_scrn($var1){
echo "tp12: ".$var1;
}
proc_scrn($var);
?>

CakePHP Relation on link

The following link is used in a list of Favours! It links to a place where the user is from but is being used inside the favour list Hence the favour variable.
I have three models Users, Places and Favours. A user has many favours and one place, a favour belongs to a user.
<?php foreach($favours as $favour): ?>
<p><?php echo $this->Html->link($favour['User']['firstname'] . ' ' . $favour['User']['lastname'], array('controller'=>'users','action'=>'view','userName'=>$favour['User']['username'])); ?> in <?php echo $this->Html->link($favour['Place']['name'], array('controller'=>'places','action'=>'view',$favour['Place']['id'])); ?> asked a favour <?php echo $favour['Favour']['datetime']; ?></p>
<h3><?php echo $this->Html->link($favour['Favour']['title'], array('controller'=>'favours','action'=>'view',$favour['Favour']['id'])); ?></h3>
How do I display the link as at the moment I get an error saying that Place is undefined.
This is the controller action for that list:
function index()
{
$favours = $this->paginate();
if (isset($this->params['requested']))
{
return $favours;
}
else
{
$this->set('favours', $favours);
}
}
Make sure you contain Place when fetching data for Favour.
This is how it should look like in your favours_controller:
function index(){
$favours = $this->Favour->find('all');
$places = $this->Favour->Place->find('all');
$this->paginate();
$this->set(compact('users', 'places');
}
This is how it should look like in your index.ctp:
<?php foreach($favours as $favour): ?>
<?php echo $this->Html->link($favour['Favour']['username'], array('controller'=>'users','action'=>'view', $favour['Favour']['username'])); ?>
<?php endforeach; ?>
<?php foreach($places as $place): ?>
<?php echo $this->Html->link($place['Place']['place'], array('controller'=>'places','action'=>'view', $place['Place']['place'])); ?>
<?php endforeach; ?>
You may also need to define the uses variable:
var $uses = array('Place');

Categories