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);
?>
Related
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);
?>
Hello Id like to know how to call the function I just written from URL?
Bellow are my php code.
<?php
require 'db.php';
function l1(){
echo "Hello there!";
}
function l2(){
echo "I have no Idea what Im doing!";
}
function l3(){
echo "I'm just a year 1 college student dont torture me sir!";
}
?>
I tried http://127.0.0.1/study/sf.php?function=l1 but it wont echo the written code.
Please point me to the right direction.
Yes you could supply that parameter into calling your user defined function:
$func = $_GET['function'];
$func();
Might as well filter the ones you have defined thru get_defined_functions
function l1(){
echo "Hello there!";
}
function l2(){
echo "I have no Idea what Im doing!";
}
function l3(){
echo "I'm just a year 1 college student dont torture me sir!";
}
$functions = $arr = get_defined_functions()['user']; // defined functions
if(!empty($_GET['function']) && in_array($_GET['function'], $functions)) {
$func = $_GET['function'];
$func();
}
Sample Output
Sidenote: function_exists can be also applied as well:
if(!empty($_GET['function']) && function_exists($_GET['function'])) {
// invoke function
}
One option you can do if use if/elseifs like so:
if($_GET['function'] == 'l1')
{
l1();
}
else if($_GET['function'] == 'l2')
{
l2();
}
Or you could use a riskier approach and call the function name directly from the input.
$functionName = $_GET['function'];
$functionName();
Edit:
Or you could use a switch statement:
switch($_GET['function'])
{
case 'l1':
l1();
break;
case 'l2':
l2();
break;
case 'l3':
l3();
break;
}
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
I have next to no experience with php as a language, and am running it a little problem in producing a Drupal theme. What I need is to execute a function once, that will return a Boolean, then use that Boolean throughout the template.
Here is what I have so far:
html.tpl.php->
<?php
function testMobile(){
return false;
}
define('isMobile', testMobile());
?>
...
<?php
if(!isMobile){
echo '<h1>NOT MOBILE</h1>';
}else{
echo '<h1>IS MOBILE</h1>';
}
?>
page.tpl.php->
<?php
if(!isMobile){
echo '<h1>IS DESKTOP</h1>';
}else{
echo '<h1>NOT DESKTOP</h1>';
}
?>
In the drupal output I get this ->
NOT MOBILE
NOT DESKTOP
along with this error message:
Notice: Use of undefined constant isMobile - assumed 'isMobile' in include() (line 77 of /Users/#/#/#/sites/all/themes/#/templates/page.tpl.php).
what am I doing wrong here? How can I most easily achieve my goal?
It seems that the defined variable is falling out of the scope of the template file. You can simply solve this by using a session variable.
Below is a code sample ...
session_start(); // not necessary with drupal
$_SESSION['isMobile'] = testMobile();
function testMobile(){
return false;
}
In your template you can add following...
<?php
if(!$_SESSION['isMobile']){
echo '<h1>IS DESKTOP</h1>';
}else{
echo '<h1>NOT DESKTOP</h1>';
}
?>
Try to define variable in template.php in hook_theme_preprocess_page(&$vars, $hook).
So template.php can looks follow way:
function testMobile(){
return false;
}
function YOURTHEME_theme_preprocess_page(&$vars, $hook) {
$vars['isMobile'] = testMobile();
}
And page.tpl.php
<?php
if(!$isMobile){
echo '<h1>IS DESKTOP</h1>';
}else{
echo '<h1>NOT DESKTOP</h1>';
}
?>
i have created below function in a file info.php to debug variable & data during page load
class Info {
static function watch($what,$msg='',$more=FALSE)
{
echo "<hr/>";
echo "<br/>".$msg.":";
if( is_array($what) || is_object($what) )
{
echo "<pre>";
print_r($what);
echo "</pre>";
}
else{
echo $what;
}
if($more)
{
echo "<br/>METHOD:".__METHOD__;
echo "<br/>LINE:".__LINE__;
}
}
}
now i call this method from another page index.php, where i inculded info.php
in this file i want to debug POST array, so i write below code
class Testpost {
__construct() { // some basic intializtion }
function getPostdata($postarray) {
$postarray=$_POST;
Info::watch($postarray,'POST ARRAY', TRUE);
}
everything is working fine but method and LINE appears below
METHOD:Info::watch();
LINE:17 // ( where this code is written in Info class)
but i wantbelow to display
METHOD: Testpost::gtPostdata()
LINE:5( where this function is called in Testpost class)
so how do i do that if i put$more=TRUE in watch() then method and line number should be diaply from the class where it is called.
can i use self:: or parent::in watch method?? or something else
please suggest me how to call magic constants from other classes or is there any other method to debug varaibale?? ( please dont suggest to use Xdebug or any other tools)
You have to use the debug_backtrace() php function.
You also have below the solution to your problem. Enjoy! :)
<?php
class Info {
static function watch($what,$msg='',$more=FALSE)
{
echo "<hr/>";
echo "<br/>".$msg.":";
if( is_array($what) || is_object($what) )
{
echo "<pre>";
print_r($what);
echo "</pre>";
}
else{
echo $what;
}
if($more)
{
$backtrace = debug_backtrace();
if (isset($backtrace[1]))
{
echo "<br/>METHOD:".$backtrace[1]['function'];
echo "<br/>LINE:".$backtrace[1]['line'];
}
}
}
}
You can not use those constants from that scope. Check out the function debug_backtrace() instead. If it gives you too much info, try to parse it.
debug_bactrace is the only way you could totally automate this, but it's a "heavy-duty" function.... very slow to execute, and needs parsing to extract the required information. It might seem cumbersome, but a far better solution is to pass the necessary information to your Info::watch method:
class Info {
static function watch($whereClass,$whereLine,$what,$msg='',$more=FALSE)
{
echo "<hr/>";
echo "<br/>".$msg.":";
if( is_array($what) || is_object($what) )
{
echo "<pre>";
print_r($what);
echo "</pre>";
}
else{
echo $what;
}
if($more)
{
echo "<br/>METHOD:".$whereClass;
echo "<br/>LINE:".$whereLine;
}
}
}
now i call this method from another page index.php, where i inculded info.php
class Testpost {
__construct() { // some basic intializtion }
function getPostdata($postarray) {
$postarray=$_POST;
Info::watch(__METHOD__,__LINE__,$postarray,'POST ARRAY', TRUE);
}