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
Related
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.
I've been taking the php course from code academy. In one of the exercises, i've tried to implement a conditional function, where it would take a parameter for how many times the function would run. Unfortunately it is not running. I'm trying to run the bark() twice with bark(2). It's only echoing once. I have tried a "do while", "if" and "for". None worked. Why is that?
<?php
class Dog{
public $numLegs = 4;
public $name;
public $speak = "Woof!";
public function bark($up){
$counter = 0;
for($counter; $counter!=$up;$counter++){
return $this->speak;
}
}
public function greet(){
return "Hello " . $this->name . "!" . "<br />";
}
public function __construct($name){
$this->name = $name;
}
}
$dog1 = new Dog("Barker");
$dog2 = new Dog("Amigo");
echo $dog1 -> bark(2);
echo $dog2 -> name;
?>
You are returning $this->speak, as soon as you return a value the entire function stops execution.
You could do something like:
public function bark($up){
$counter = 0;
$return = '';
for($counter; $counter<$up;$counter++){
$return .= $this->speak;
}
return $return;
}
To add another solution, without using for at all using array_fill() to create an array of the wanted size and content (since it is always the same text) and then simply implode() to receive a String as result.
public function bark($up){
return implode(array_fill(1, $up, $this->speak));
}
return inside the for loop exits from the bark function. So the dog barks only once.
public function bark($up){
$counter = 0;
for($counter; $counter!=$up;$counter++){
echo $this->speak;
}
}
$dog1 -> bark(2);
You have to change these lines:
return $this->speak;
To:
echo $this->speak;
And
echo $dog1->bark(2);
To:
dog1->bark(2);
The return statement stops immediatly the method, this is the reason you are getting only one echo
What you want to do is run the bark function in a for loop, not have a for loop in the bark function.
public function bark(){
return $this->speak;
}
for($i = 0; $i < 2; $i++){
echo $dog1 -> bark();
}
The problem with looping inside the bark function mostly comes from the fact that you lose a lot of flexibility.
You could echo right in there, but outputting data from an object's method is far from ideal. What if you need to perform some kind of logic on the output?
You could also concatenate within the function, but then again, what if you need to format the output? Then you'd have to split the output again, which defeats the purpose.
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
I was looking at the source for Drupal 7, and I found some things I hadn't seen before. I did some initial looking in the php manual, but it didn't explain these examples.
What does the keyword static do to a variable inside a function?
function module_load_all($bootstrap = FALSE) {
static $has_run = FALSE
It makes the function remember the value of the given variable ($has_run in your example) between multiple calls.
You could use this for different purposes, for example:
function doStuff() {
static $cache = null;
if ($cache === null) {
$cache = '%heavy database stuff or something%';
}
// code using $cache
}
In this example, the if would only be executed once. Even if multiple calls to doStuff would occur.
Seems like nobody mentioned so far, that static variables inside different instances of the same class remain their state. So be careful when writing OOP code.
Consider this:
class Foo
{
public function call()
{
static $test = 0;
$test++;
echo $test . PHP_EOL;
}
}
$a = new Foo();
$a->call(); // 1
$a->call(); // 2
$a->call(); // 3
$b = new Foo();
$b->call(); // 4
$b->call(); // 5
If you want a static variable to remember its state only for current class instance, you'd better stick to a class property, like this:
class Bar
{
private $test = 0;
public function call()
{
$this->test++;
echo $this->test . PHP_EOL;
}
}
$a = new Bar();
$a->call(); // 1
$a->call(); // 2
$a->call(); // 3
$b = new Bar();
$b->call(); // 1
$b->call(); // 2
Given the following example:
function a($s){
static $v = 10;
echo $v;
$v = $s;
}
First call of
a(20);
will output 10, then $v to be 20. The variable $v is not garbage collected after the function ends, as it is a static (non-dynamic) variable. The variable will stay within its scope until the script totally ends.
Therefore, the following call of
a(15);
will then output 20, and then set $v to be 15.
Static works the same way as it does in a class. The variable is shared across all instances of a function. In your particular example, once the function is run, $has_run is set to TRUE. All future runs of the function will have $has_run = TRUE. This is particularly useful in recursive functions (as an alternative to passing the count).
A static variable exists only in a
local function scope, but it does not
lose its value when program execution
leaves this scope.
See http://php.net/manual/en/language.variables.scope.php
To expand on the answer of Yang
If you extend a class with static variables, the individual extended classes will hold their "own" referenced static that's shared between instances.
<?php
class base {
function calc() {
static $foo = 0;
$foo++;
return $foo;
}
}
class one extends base {
function e() {
echo "one:".$this->calc().PHP_EOL;
}
}
class two extends base {
function p() {
echo "two:".$this->calc().PHP_EOL;
}
}
$x = new one();
$y = new two();
$x_repeat = new one();
$x->e();
$y->p();
$x->e();
$x_repeat->e();
$x->e();
$x_repeat->e();
$y->p();
outputs:
one:1
two:1
one:2
one:3 <-- x_repeat
one:4
one:5 <-- x_repeat
two:2
http://ideone.com/W4W5Qv
static variable in a function means that no matter how many times you call the function, there's only 1 variable.
<?php
class Foo{
protected static $test = 'Foo';
function yourstatic(){
static $test = 0;
$test++;
echo $test . "\n";
}
function bar(){
$test = 0;
$test++;
echo $test . "\n";
}
}
$f = new Foo();
$f->yourstatic(); // 1
$f->yourstatic(); // 2
$f->yourstatic(); // 3
$f->bar(); // 1
$f->bar(); // 1
$f->bar(); // 1
?>
Inside a function, static means that the variable will retain its value each time the function is called during the life of the page load.
Therefore in the example you've given, if you call a function twice, if it set $has_run to true, then the function would be able to know that it had previously been called because $has_run would still be equal to true when the function starts the second time.
The usage of the static keyword in this context is explained in the PHP manual here: http://php.net/manual/en/language.variables.scope.php
Is it possible to include one function inside another? To learn functions, I'm trying to create a combat sequence using PHP. The sequence would look like this:
Dice would roll, assigning numbers to variables;
Hero1 attack results are printed;
Dice would roll, assigning numbers to variables;
Hereo2 attack results are printed;
Dice would roll, assigning numbers to variables;
Hero3 attack results are printed.
The dice rolling would be an automated function. Here is the code:
<?
rollSim();
combatSim();
function rollSim() {
$hAttack = rand(1,20);
$mDefend = rand(1,20);
$mAttack = rand(1,20);
$hDefend = rand(1,20);
$mDamage = rand(10,25);
$hDamage = rand(1,20);
} // end rollSim
function combatSim() {
rollSim();
if ($hAttack>$mDefend) {
print "Hero hit monster for $hDamage damage.<br>";
} else if ($hAttack<=$mDefend) {
print "Hero missed monster.";
}
} // end combatSim
?>
Your rollSim() function should return the rolled numbers rather than setting some variables and trying to use them in your other function. I would return them in an associative array, like this:
function rollSim() {
$roll['hAttack'] = rand(1,20);
$roll['mDefend'] = rand(1,20);
$roll['mAttack'] = rand(1,20);
$roll['hDefend'] = rand(1,20);
$roll['mDamage'] = rand(10,25);
$roll['hDamage'] = rand(1,20);
return $roll;
}
function combatSim() {
$roll = rollSim();
if ($roll['hAttack'] > $roll['mDefend']) {
print "Hero hit monster for {$roll['hDamage']} damage.<br>";
} else if ($roll['hAttack'] <= $roll['mDefend']) {
print "Hero missed monster.";
}
}
No, you can't really do what you're asking. Even if you embedded the declaration of rollSim() inside the definition of combatSim() (which you can do, that's legal but has no real effects), the variables you're setting in rollSim() would still be local to it and inaccessible by combatSim().
You need a better way of passing around the information you're concerned with. Jeremy Ruten details a good way. Another way would be to define an object that's responsible for modeling your combat event and have rollSim() and combatSim() both be methods on it.
class myCombat {
private $hAttack;
private $mDefend;
private $mAttack;
private $hDefend;
private $mDamage;
private $hDamage;
function rollSim() {
$this->hAttack = rand(1, 20);
$this->mDefend = rand(1, 20);
$this->mAttack = rand(1, 20);
$this->hDefend = rand(1, 20);
$this->mDamage = rand(10, 25);
$this->hDamage = rand(1, 20);
}
function combatSim() {
$this->rollSim();
if($this->hAttack > $this->mDefend)
echo 'Hero hit monster for ' . $this->hDamage . ' damage.<br />';
else
echo 'Hero missed monster';
}
}
$combat = new myCombat;
$combat->combatSim();
You can call functions from one another, certainly... but I think you want to use the scope of one in another, correct?
Sharing scope is a messy business. You're better off passing arguments.
If you want to define functions within function in PHP you can do it like this:
function a()
{
function b()
{
echo 'I am b';
}
function c()
{
echo 'I am c';
}
}
a();
b();
c();
You must call the parent function first, then the functions inside.
here is the simple example call function within function
class Percobaan{
public function coba(){
return "return value";
}
public function call(){
//call coba function
return $this->coba();
}
} // end of class percobaan
//call the method
$klass = new Percobaan();
echo $klass->call();
the output willbe :
"return value"