I am trying to print score automatically, if the question is correct it should increment the score. I tried this function:
function checkscore ()
{
static $score = 0;
if ($_SESSION['result'] == "Correct")
$score++;
return $score;
}
this function returns 1 if the question is correct or 0 if the question is wrong. But $score does not increment in any case. How can I make increment the $score variable?
Do not init $score variable, like this:
function checkscore ()
{
static $score; // Here without initialization
if (is_null($score)) {
$score = 0;
}
if ($_SESSION['result'] == "Correct") {
$score++;
}
return $score;
}
$_SESSION['result'] = 'Correct';
checkscore(); // 1
checkscore(); // 2
...
There is nothing wrong with your code but I imaging you are expecting the static variable to remain in existance over multiple calls to this script.
That is not how static works!
If you use it like this:
function checkscore ()
{
static $score = 0;
if ($_SESSION['result'] == "Correct")
$score ++;
return $score;
}
echo checkscore () . '<br>';
echo checkscore () . '<br>';
echo checkscore () . '<br>';
You will get the result:
1
2
3
But if you are calling the script from a form where the user answers ONE question and the form is submitted to this script static will not work as you expect. The static variable will be initialised to zero on each call to the script.
If you want to remember the value of $score across multiple calls to the script you will have to save it in the $_SESSION something like this
function checkscore ()
{
$score = isset($_SESSION['score']) ? $_SESSION['score'] : 0;
if ($_SESSION['result'] == "Correct")
$score ++;
$_SESSION['score'] = $score;
return $score;
}
You need to pass the variable as the argument of function.Try like this
function checkscore ($score){
if ($_SESSION['result'] == "Correct")
$score ++;
return $score;
}
//Function call example;
checkscore (1);
static variable gets initialized only once even re-initialization will not effect value of variable, A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.
function checkscore ()
{
static $score = 0;
if ($_SESSION['result'] == "Correct")
$score++;
return $score;
}
Nothing wrong with your code check wether you may be doing it wrong on the calling section or handling return value.
You can try this also, pass by refrence
function checkscore (&$score){
if ($_SESSION['result'] == "Correct"){
$score ++;
return 'correct';
}else{
return 'wrong';
}
//Function call example;
$score = 1;
checkscore ($score);
echo $score;
In this way you will return two values from a function one will say correct or wrong and reference variable will update score as well.
Related
<?php
class SimpleClass{
var $number1;
var $number2;
public function input_two_no($num1,$num2){
$this->number1=$num1;
$this->number2=$num2;
}
public function the_sum(){
$total = $number1+$number2;
return $total;
}
public function output_the_sum(){
echo $total;
}
$numbers = new SimpleClass;
$numbers->input_two_no(10,5);
$numbers->the_sum();
$numbers->output_the_sum();
}
?>
Please point out where i am going wrong in this.I am not getting the output yet.
There are several things you're doing wrong, such as:
Take this code block $numbers = new SimpleClass; ... $numbers->output_the_sum(); outside of the class.
See this statement inside the_sum() method,
$total = $number1+$number2;
You didn't declare any local variables named $number1 and $number2 inside the_sum() method. Instead, you should make use of the instance variables here.
See this statement in output_the_sum() method,
echo $total;
You didn't declare any local variable named $total inside output_the_sum() method. Instead, create an instance variable named $total and store the sum value in this instance variable. Later, you can display the total sum value using echo $this->total;.
So your code should be like this:
class SimpleClass{
var $number1;
var $number2;
var $total;
public function input_two_no($num1,$num2){
$this->number1=$num1;
$this->number2=$num2;
}
public function the_sum(){
$this->total = $this->number1+$this->number2;
}
public function output_the_sum(){
echo $this->total;
}
}
$numbers = new SimpleClass;
$numbers->input_two_no(10,5);
$numbers->the_sum();
$numbers->output_the_sum();
First off, you don't need the 2 Methods. input_two_no($num1,$num2) and output_the_sum(). You may, however, create a basic constructor method. Secondly, to access member-variables (Properties), you need to use php object-access notation (->). your class should have been as shown below. the sum method itself returns the sum of the 2 numbers passed as arguments.
class SimpleClass{
var $number1;
var $number2;
public function __construct($num1=null, $num2=null){
$this->number1 = $num1;
$this->number2 = $num2;
}
public function the_sum($number1=null, $number2=null){
if(!is_null($number1) && !is_null($number2)){
return null;
}
if( (!is_int($number1) || !is_float($number1) || !is_double($number1)) &&
(!is_int($number2) || !is_float($number2) || !is_double($number2))
){
return 'Numeric inputs only...';
}
$this->number1 = $number1;
$this->number2 = $number2;
return $this->number1 + $this->number2;
}
}
$numbers = new SimpleClass;
$output = $numbers->the_sum(10,5);
echo $output; //<== YIELDS 15
I'm having hard time accomplishing one simple task. I have a method that would generate random number and depending on the outcome assign specific outcome to an array variable. What i want to do is get that array variable through instance method which would be called from the other class.
<?php
class MyClass
{
public $results = array(array());
public function simulated_games()
{
$game_series1=array(23,34,56);
$game_series2=array(31,42,67);
$iter_wins=array(array());
for($i=0; $i<10;$i++)
{
$random = rand(0,100);
for($b=0; $b<1;$b++)
{
if($random <= $game_series1[0])
{
$iter_wins[$i][$b]=3;
}
else if($random <= $game_series2[0]+$game_series2[1])
{
$iter_wins[$i][$b]=1;
}
}
}
$results=$iter_wins;
}
>here i create method just to return variable
public function get_simulated_games()
{
return $this->results;
}
}
<?php
$a= new MyClass();
$a->simulated_games();
$array = array();
>here is the issue, it return just 1, but supposed to return range numbers
$array=$a->get_simulated_games();
for($f=0; $f<sizeof($array);$f++)
{
for($g=0; $g<5;$g++)
{
echo $array[$f][$g];
}
echo '<br>';
}
?>
You have the error in results.
You modify interal function variable which is not set instead of class variable
change
$results=$iter_wins;
to
$this->results=$iter_wins;
I have a function which I call multiple times within a script. The value returned from the function will always be the same. I would rather not execute all the script within the function each time since the returned value is always the same. I am not using OOP so can't assign it to a object property and do the script in the constructor.
Below is my attempt. It doesn't work since $status is not set until it later is defined as a static variable. How can I accomplish my goal?
function checkStatus()
{
if(!isset($status))
{
//Do some script to determine $cond
if($cond) {static $status=0;}
else {static $status=1;}
}
return $status;
}
This should do what you need:
function checkStatus()
{
static $status;
if(!isset($status))
{
if (TRUE) // Whatever your truth condition will be
{
$status = 1;
}
else
{
$status = 0;
}
}
return $status;
}
You could pass the variable by reference: http://www.php.net/manual/en/language.references.pass.php
function checkStatus(&$status)
{
//Do some script to determine $cond
if($status == 0) {
$status=1;
}
else {
$status=0;
}
}
$status = 0;
checkStatus($status);
echo $status; //this should display 1;
I'm trying to call a function with a php variable variable. You'll see in my code in function mainFunction(). If it's not possible to do it this way, is there a better way to do it, that avoids any more code? I wish it would work this way.
<?php
$a = 1;
$b = 1;
if ( $a == $b ) {
$exampleFunction = 'exampleOne';
} else {
$exampleFunction = 'exampleTwo';
}
//----------------------------------------------
mainFunction();
function mainFunction() {
global $exampleFunction;
echo 'This is mainFunction <br>';
$$exampleFunction();//Here's where I'm stuck.
}
function exampleOne() {
echo 'This is example one <br>';
}
function exampleTwo() {
echo 'This is example two <br>';
}
?>
A way to solve this problem would be to use PHP's call_user_func function. Here is the modified code (it also removes the global variable):
Code Example
<?php
$a = 1;
$b = 1;
// I'm just using this to hold the function name,
// to get rid of the global keyword. It will be passed
// as an argument to our mainFunction()
$exampleFunction = '';
if ($a == $b) {
$exampleFunction = 'exampleOne';
} else {
$exampleFunction = 'exampleTwo';
}
//----------------------------------------------
mainFunction($exampleFunction);
function mainFunction($func) {
echo 'This is mainFunction <br>';
// Use PHP's call_user_func. We are also checking to make sure
// the function exists here.
if (function_exists($func)) {
// This will call the function.
call_user_func($func);
}
}
function exampleOne() {
echo 'This is example one <br>';
}
function exampleTwo() {
echo 'This is example two <br>';
}
Output
When I run this code, it produces the following output:
This is mainFunction
This is example two
Try like
if ( $a == $b ) {
$exampleFunction = exampleOne();
} else {
$exampleFunction = exampleTwo();
}
and your functions should return like
function exampleOne() {
return 'This is example one <br>';
}
function exampleTwo() {
return 'This is example two <br>';
}
OR if you want to call them through the variable try to replace like
function mainFunction() {
global $exampleFunction;
echo 'This is mainFunction <br>';
$exampleFunction();
}
Try with $exampleFunction(); instead of $$exampleFunction();
OR
use call_user_func($exampleFunction)
check this way :-
function mainFunction() {
global $exampleFunction;
echo 'This is mainFunction <br>';
$exampleFunction();
}
Use just $exampleFunction, without $$:
<?php
function mainFunction() {
global $exampleFunction;
echo 'This is mainFunction <br>';
$exampleFunction();
}
?>
See manual of variable functions, not variable variables.
P.S.: Also, I suggest $exampleFunction to be an argument of mailFunction, rather than use globals.
I have a problem trying to run a code inside the loop, my loop consist of a function.
Here is my coding:
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++){
$val = $new[$i];
function myfunction($value) {
//Do something
}
echo $val;
}
The problem is the code outputs only the 1st value in my array. I am very confused, am I not suppose to declare a function inside the loop?
Your code ends up with Fatal error, since at the second iteration it tries to redeclare function myfunction. That's why it is printing only first value of array.
In order to avoid that fatal error you can check if that function has been already defined using function_exists() function like this:
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++)
{
$val = $new[$i];
if(!function_exists('myfunction'))
{
function myfunction($value) {
//Do something
}
}
echo $val;
}
PHP is a scripting language and it is syntactically correct to declare a function inside for loop or inside if statement, but it is a bad practice and can cause a lot of errors afterwards.
The best way is to declare a function outside loop, and, if needed, call it from within a loop like this:
<?php
function myfunction($value) {
//Do something
}
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++)
{
$val = $new[$i];
myfunction($value); //may you was intended to pass $val here?
echo $val;
}
Don't declare the function inside the loop, declare it before the loop and then call to it inside the loop with myFunction($value);
the function should be in a separate procedure
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++)
{
$val = $new[$i];
myfunction($val)
echo $val;
}
then this is your function
function myfunction($value)
{
//Do something
}
Declare the function outside of the loop
either return a value from the function, or let the function output data
For example:
function myfunction($value) {
//Do something
echo $value;
}
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++) {
myfunction($new[$i]);
}
I am assuming you want to print out the first 4 elements of the array.
do something like this
function myfunction() {
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++){
$val = $new[$i];
echo $val;
}
}
myfunction();
You should declare the function outside the loop
function myfunction($value) {
return ($value + 25); // an example
}
$new = array(1,2,3,4);
for($i = 0; $i < count($new); $i++){
echo myfunction($new[$i]);
}
Also you should set the loop from 0 to the end of the array, so if you'll have more than 4 entries in the array the code should be ok
You can declare an anonymous function instead:
for ($i=0; $i<=3; $i++) {
// code
$myFunction = function($value) { /* code */ }
$myFunction($val);
// code
}
that is not the right way to do it...
first declare the function outside the loop, then call the function in the loop
function myfunction($value) {
//Do something
}
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++){
$val = $new[$i];
myfunction( $val); //call function where u wanted... here (in your case)
echo $val;
}
You are not suposed to declare the function inside a loop...