Call function within a function PHP - php

1 function foo($i){
2 return bar($i)*4;
3 function bar($i){
4 return $i*4;
5 }
6 }
7 echo foo(4);
return
Fatal error: Call to undefined function bar() in /var/www/index.php on line 2
why doesn't it work? it works well in javascript, while it works when i do this:
function foo($i){
return bar($i)*4;
}
function bar($i){
return $i*4;
}

Define the function above your return value, otherwise it never gets executed.
<?php
function foo($i){
function bar($i){
return $i*4;
}
return bar($i)*4;
}
echo foo(4);
?>

It doesn't work as you are calling bar() before it has been created.
See example 2 here:- http://www.php.net/manual/en/functions.user-defined.php

Your code never reach function bar(...), therefore it's never defined.
You need to put your bar() function before your foo() or before the return bar. (Answer based on your first example).
With your second example you probably define bar() before you use foo() therefore bar() is defined and it works fine.
So as long as you have your function defined when you hit a certain spot in your code it works fine, no matter if it's called from within another function.

If you define function within another function, it can be accessed directly, but after calling parent function.
For example:
function a () {
function b() {
echo "I am b.";
}
echo "I am a.<br/>";
}
//b(); Fatal error: Call to undefined function b() in E:\..\func.php on line 8
a(); // Print I am a.
b(); // Print I am b.

Execution not execute after return statement
change your code like this
function foo($i){
function bar($i){
return $i*4;
}
return bar($i)*4;
}
echo foo(4);

For the sake of having a "recent" answer, here's what I did:
function printRx($conn, $patient)
{
function rows($rows, $tod)
{
for ($x = 0; $x < count($tod); $x++) {
if ($tod[$x] == 1) {
$rows++;
break;
}
}
return $rows;
}
$tod['prn'] = (explode('|', $row['prn'])) ?? null;
$rows = rows($rows, $tod['prn']);
return;
}
Works beautifully

Related

function call from another function in php and php script should run backgound

I have created a class A() with two functions i.e a() and b().
Function a() have a condition if(state==true) then break operation.
If the condition is false, then it should call function b().
Function b() will call again function a() untill function's a() condition gets true.
Below is my code :
class name
{
public function a($id)
{
if() {} else {
b($id);
}
}
public function b($id)
{
sleep(10);
a();
}
}
$id = 4;
$oba = new name();
$oba->a($id);
hi hussain are you wanted to do something like this?
<?php
class name{
public function a($id)
{
if($id==4){
echo"condition statisfied";
return true;
}
}
}
$id= 0;
$a_obj = new name();
while ( $id<= 4) {
$a_obj->a($id);
echo "id count :".$id."<br>";
$id++;
}
?>
this is the efficeint way to perform what you wanted to do.
and for running script in background you can refer this link
and please explain question properly.
soo far you don't have a function called a() as your taking it as a constructor.

Why can't I return value using obj in class when i use recursion?

Writing a factorial program using recursion ,class and function.
Shows error: Uncaught Error: Call to undefined function fact()
class factorial{
public function fact($n){
if($n==1){
return 1;
}
else{
return $n*fact($n-1);
}
}
}
$obj= new factorial();
$print=$obj->fact(3);
echo $print;
The error is in line number 11 ie;
return $n*fact($n-1);
the method fact was not called properly in this. You have to use $this operator to call the function within that class on any method.
So, you just have to change that to $this->fact($n-1)
For convenience I am providing the whole revised code here below, have a look into it.
<?php
//Enter your code here, enjoy!
class factorial{
public function fact($n){
if($n==1){
return 1;
}
else{
return $n*$this->fact($n-1);
}
}
}
$obj= new factorial();
$print=$obj->fact(3);
echo $print;
You can check the code working here in the link : http://sandbox.onlinephpfunctions.com/code/1c1131c1ade963048266a0e426e9357232aaddd5

Check the method was called in php

I have following php code in basic.php. How can I determine if the method row() was called? When I write next <?php $basic->row(); ?> it shows something like this - the method was defined!
Example
$basic->container(); // container was called
$basic->container(); // when called again, i need show some warning - CONTAINER CAN BE PUT ONLY ONCE and using exit() for example
This is the solution what i need
public function container(){
static $container = false;
if ( $container ){ return; } else { print '<div class="container">'; } $container = true;
}
If you want to know if an object has a method or not before calling it, you can use method_exists.
if(method_exists($basic, 'row')) {
$basic->row();
}
Use the echo construct inside the row function like this:
// your code
function row(){
echo "Function called!";
....
}
This will print the text "Function called!" everytime you call the function.
I just add it as an answer ... try smthg like this:
function row(){
if($wascalled === true) {
echo "The function was called";
}
//your Code here
$wascalled = true;
}
So, the first time you call the function, nothing happens, if you call it more, the message will appear. It looks ugly and i dont see much sense in it, but it seems to work.
I did not understand if you mean really a call or if the method is defined.
As #Prasanth said, if you mean if the method is defined - method_exists will be a solution.
Otherwise, you can check my answer here: Cahining pattern
It's related to your problem, as you need a generic way to register a method been called before.
You, ofcourse, can write down
public $_row = false;
public function row() {
$this->_row = true;
// some stuff
}
and later:
if (!$basic->_row) {
$basic->row();
}
You just need a property where you will set a value, which corresponds to your script later. I.e. here the default value is false - it means the method hasn't been called yet. Once method is called, it changes it to true. You are testing if the value is default (false) then call.
You may not change the value to true, but to the string you wanted. E.g. $this->_row = 'the method was defined!' Or set to true and print the string, if $this->_row == true.
Reference
bool function_exists ( string $function_name )
Parameters The $function_name, as a string.
Returns TRUE if function_name exists and is a function, FALSE otherwise.
Note:
This function will return FALSE for constructs, such as include_once and echo.
<?php
if (function_exists('function_name')) {
echo "IMAP functions are available.<br />\n";
} else {
echo "IMAP functions are not available.<br />\n";
}
?>
Take this as an example
<?php
if (function_exists('foo')) {
print "foo defined\\n";
} else {
print "foo not defined\\n";
}
function foo() {}
if (function_exists('bar')) {
print "bar defined\\n";
} else {
print "defining bar\\n";
function bar() {}
}
print "calling bar\\n";
bar(); // ok to call function conditionally defined earlier
print "calling baz\\n";
baz(); // ok to call function unconditionally defined later
function baz() {}
qux(); // NOT ok to call function conditionally defined later
if (!function_exists('qux')) {
function qux() {}
}
?>
Prints:
foo defined
defining bar
calling bar
calling baz
PHP Fatal error: Call to undefined function qux()
Alternative method
You can use magic method __call.
class Basic{
function row(){
print ' Call method '.__METHOD__.'<br/>';
}
function __call($method,$params){
if (method_exists($this, $method)) {
call_user_func_array(array($this, $method), $params);
}else{
print 'Class '.__CLASS__.' hasn`t method "'.$method.'"<br/>';
}
}
}
$basic = new Basic();
$basic->row();
$basic->fetch();
// output
Call method Basic::row
Class Basic hasn`t method "fetch"

Calculate number of function calls in the same function

How to calculate(determine) in php the total number of a function calls but the result of this must be in the same function for which I calculate this number.
Exemple:
The test() function is called 100 times(this number is variable and so I don't know it from beginning). I want to find this number in the block of function
test();
function test(){
$no_calls =....
echo $no_calls;
}
I want the message from echo to be shown only once not to every call of function.
use a static variable, like this
function test(){
static $no_calls = 0;
...
++$no_calls;
}
$no_calls will keep its value between calls
In response to your edit, you could do something like this:
function test() {
static $no_calls = 0;
++$no_calls;
...
return $no_calls;
}
test();
test();
test();
$final = test();
echo $final; // will be 4
ok, let's try this a third time:
function test($last_time = false) {
static $no_calls = 0;
++$no_calls;
...
if($last_time)
{
echo $no_calls;
}
}
test();
test();
test();
test(true); // will echo 4
OK, let's try this one more time:
class Test {
private $no_calls;
function test()
{
...
++$this->no_calls;
}
function __destruct()
{
echo $this->no_calls;
}
}
$test = new Test();
$test->test();
$test->test();
$test->test();
$test->test();
//when $test falls out of scope, 4 will be echoed.
so, we need to magically echo the number of times a function is called: only once, inside the function, without using classes, and without telling the function that it is the last call. Hold on to your hats (warning, I do not suggest using this code for many reasons (but you leave me no choice), and it WILL NOT work if there is to be any output in between function calls, including by the function itself):
function test() {
static $no_calls = 1;
if($no_calls == 1)
{
ob_start();
}
else
{
++$no_calls;
ob_clean();
}
echo $no_calls;
}
In this instance, when the script terminates, the output buffering left open will automatically flush to the browser.
<?php
test();
test();
test();
test();
$NoOfCalls=0;
function test(){
global $NoOfCalls;
echo ++$NoOfCalls;
}
function test() {
static $calls = 0;
$calls++;
echo "this function has been called $calls times";
}
test(); // 1 times
test(); // 2 times
test(); // 3 times
If you need that calls value to be available outside of the function, you'll either have to return it from the function (return $calls, or assign it to a global variable somewhere.
This should help:
function test() {
static $count = 0;
$count++;
...
}
You can make global variable and increment it in function. And when you check total call count, you can use that variable.
Sloppy code, but it should be understandable enough. It utilizes the __destruct of the object to only print the summary once. Also it uses debug_backtrace to automagically detect what function is calling it. This will work if you call multiple functions too (like test, test2, some_random_function).
<?php
class Counter {
private $_count = array();
public function count_call()
{
list(, $prev) = debug_backtrace();
$this->_count[$prev['function']] = isset($this->_count[$prev['function']])
? $this->_count[$prev['function']] + 1
: 1;
}
public function __destruct(){
echo '<h2>Calls per function:</h2>';
echo '<pre>';
var_dump($this->_count);
echo '</pre>';
}
}
$counter = new Counter();
function test() {
global $counter;
$counter->count_call();
echo 'called test<br />';
}
$rand = rand(5, 10);
echo "calls to be made: {$rand}<br />";
for ($i = 0; $i < $rand; $i++) {
test();
}
While i was looking for new functions to handle some function call counts. i know that the xhprof extensions can collect thouse things and much more which can be very interessting. without implementing debug code

Reference to static method in PHP?

In PHP, I am able to use a normal function as a variable without problem, but I haven't figured out how to use a static method. Am I just missing the right syntax, or is this not possible?
(EDIT: the first suggested answer does not seem to work. I've extended my example to show the errors returned.)
function foo1($a,$b) { return $a/$b; }
class Bar
{
static function foo2($a,$b) { return $a/$b; }
public function UseReferences()
{
// WORKS FINE:
$fn = foo1;
print $fn(1,1);
// WORKS FINE:
print self::foo2(2,1);
print Bar::foo2(3,1);
// DOES NOT WORK ... error: Undefined class constant 'foo2'
//$fn = self::foo2;
//print $fn(4,1);
// DOES NOT WORK ... error: Call to undefined function self::foo2()
//$fn = 'self::foo2';
//print $fn(5,1);
// DOES NOT WORK ... error: Call to undefined function Bar::foo2()
//$fn = 'Bar::foo2';
//print $fn(5,1);
}
}
$x = new Bar();
$x->UseReferences();
(I am using PHP v5.2.6 -- does the answer change depending on version too?)
PHP handles callbacks as strings, not function pointers. The reason your first test works is because the PHP interpreter assumes foo1 as a string. If you have E_NOTICE level error enabled, you should see proof of that.
"Use of undefined constant foo1 - assumed 'foo1'"
You can't call static methods this way, unfortunately. The scope (class) is relevant so you need to use call_user_func instead.
<?php
function foo1($a,$b) { return $a/$b; }
class Bar
{
public static function foo2($a,$b) { return $a/$b; }
public function UseReferences()
{
$fn = 'foo1';
echo $fn(6,3);
$fn = array( 'self', 'foo2' );
print call_user_func( $fn, 6, 2 );
}
}
$b = new Bar;
$b->UseReferences();
In php 5.2, you can use a variable as the method name in a static call, but to use a variable as the class name, you'll have to use callbacks as described by BaileyP.
However, from php 5.3, you can use a variable as the class name in a static call. So:
class Bar
{
public static function foo2($a,$b) { return $a/$b; }
public function UseReferences()
{
$method = 'foo2';
print Bar::$method(6,2); // works in php 5.2.6
$class = 'Bar';
print $class::$method(6,2); // works in php 5.3
}
}
$b = new Bar;
$b->UseReferences();
?>
You could use the full name of static method, including the namespace.
<?php
function foo($method)
{
return $method('argument');
}
foo('YourClass::staticMethod');
foo('Namespace\YourClass::staticMethod');
The name array array('YourClass', 'staticMethod') is equal to it. But I think the string may be more clear for reading.
In PHP 5.3.0, you could also do the following:
<?php
class Foo {
static function Bar($a, $b) {
if ($a == $b)
return 0;
return ($a < $b) ? -1 : 1;
}
function RBar($a, $b) {
if ($a == $b)
return 0;
return ($a < $b) ? 1 : -1;
}
}
$vals = array(3,2,6,4,1);
$cmpFunc = array('Foo', 'Bar');
usort($vals, $cmpFunc);
// This would also work:
$fooInstance = new Foo();
$cmpFunc = array('fooInstance', 'RBar');
// Or
// $cmpFunc = array('fooInstance', 'Bar');
usort($vals, $cmpFunc);
?>
Coming from a javascript background and being spoiled by it, I just coded this:
function staticFunctionReference($name)
{
return function() use ($name)
{
$className = strstr($name, '::', true);
if (class_exists(__NAMESPACE__."\\$className")) $name = __NAMESPACE__."\\$name";
return call_user_func_array($name, func_get_args());
};
}
To use it:
$foo = staticFunctionReference('Foo::bar');
$foo('some', 'parameters');
It's a function that returns a function that calls the function you wanted to call. Sounds fancy but as you can see in practice it's piece of cake.
Works with namespaces and the returned function should work just like the static method - parameters work the same.
This seems to work for me:
<?php
class Foo{
static function Calc($x,$y){
return $x + $y;
}
public function Test(){
$z = self::Calc(3,4);
echo("z = ".$z);
}
}
$foo = new Foo();
$foo->Test();
?>
In addition to what was said you can also use PHP's reflection capabilities:
class Bar {
public static function foo($foo, $bar) {
return $foo . ' ' . $bar;
}
public function useReferences () {
$method = new ReflectionMethod($this, 'foo');
// Note NULL as the first argument for a static call
$result = $method->invoke(NULL, '123', 'xyz');
}
}
"A member or method declared with static can not be accessed with a variable that is an instance of the object and cannot be re-defined in an extending class"
(http://theserverpages.com/php/manual/en/language.oop5.static.php)

Categories