Why the Functions aren't defined ? PHP - php

What do I have to do so that I can use the standard php functions without creating an instance of a Math_functions Class ?
<?php
class Math_functions {
public static function evenNumber($number) {
return !($number & 1);
}
public static function natual_sum($n) {
while ($n) {
if (evenNumber($n)) {
$sum = $sum + $n;
}
$n--;
}
return $sum;
}
}
echo natual_sum(4);
?>

This is a static function. You have to access it using class name. Use like this
Math_functions::natual_sum(4);

Just put the functions into a PHP File.
You don't NEED the class
Example:
<?php
function evenNumber($number) {
return !($number & 1);
}
function natual_sum($n) {
while ($n) {
if (evenNumber($n)) {
$sum = $sum + $n;
}
$n--;
}
return $sum;
}
echo natual_sum(4);
?>

Related

PHP: Increment the variable each time you run the function

I have a function in my Helper Class that should increment the variable each time the function is called.
Here is my code:
<?php
class Helper
{
public static $count;
public static function voiceHelper($questionArray)
{
$count = self::$count;
// $count = 0;
if(count($questionArray) >= $count)
{
$count++;
return $count;
} else if($count > count($questionArray))
{
$count == 0;
return $count;
}
}
}
I expect that the count variable will increment each time the function is called but it still remains 1.
Try:
class Helper
{
public static $count;
public static function voiceHelper($questionArray)
{
// $count = 0;
if(count($questionArray) >= $count)
{
self::$count++;
return self::$count;
} else if($count > count($questionArray))
{
self::$count = 0;
return self::$count;
}
}
}
Looks like you are just incrementing the $count without adding it to the static count property. Therefore you will always get 1. Instead actually increment the static count property.
You have to use self::$count everywhere:
<?php
class Helper
{
public static $count;
public static function voiceHelper($questionArray)
{
if(count($questionArray) >= self::$count)
{
self::$count++;
return self::$count;
}
if(self::$count > count($questionArray))
{
self::$count = 0; // change == to = as it's assignment
return self::$count;
}
}
}
Output:- https://3v4l.org/EaEqA And https://3v4l.org/pto7m
Note:- You did increment in the $count without adding it to the static count property. That's why you always got 1.

Call to undefined function factorial()

my code is simple. but it gives me the error above that functorial function inside the function is undefined . why ? thanks?
<?php
class fact
{
public function factorial($number) {
if ($number < 2) {
return 1;
} else {
return ($number * factorial($number-1));
}
}
}
$obj = new fact();
var_dump($obj->factorial(6));
?>
Referencing factorial will look for a global function of that name. But you've written it as a method, so it must be called specifically on the object:
return ($number * $this->factorial($number-1));
$this-> references the object instance it's being called within.
The recursion call need to be prefixed with $this as follows:
<?php
class fact
{
public function factorial($number) {
if ($number < 2) {
return 1;
} else {
return ($number * $this->factorial($number-1));
}
}
}
$obj = new fact();
var_dump($obj->factorial(6));

Trying to stack values with PHP

Im currently trying to make a little dice game in php. Right now Im trying to make a "currentscore" where all the points from a rand(1,6) are stacked into a single variable.
Here is the class Im doing this in:
<?php
class CDice {
public $roll;
public $currentscore;
public function Roll()
{
$this->roll = rand(1,6);
return $this->roll;
}
public function currentScore()
{
$this->currentscore += $this->roll;
return $this->currentscore;
}
}
I don't under stand why $this->currentscore += $this->roll; doesn't work.
You do realise that at the end of execution of this class no values are kept right? If you wish to transfer over this data to the next page render, you should use PHP sessions.
<?php
class CDice {
public $roll;
public $currentscore = 0;
public function Roll(){
$this->roll = rand(1,6);
$this->currentscore += $this->roll;
return $this->roll;
}
public function currentScore(){
return $this->currentscore;
}
public function __construct(){
if(session_status() == PHP_SESSION_ACTIVE){
$this->currentscore = isset($_SESSION['dice.score']) ? $_SESSION['dice.score'] ? 0;
# In PHP 7.0
# $this->currentscore = $_SESSION['dice.score'] ?? 0;
} else {
echo 'session has not been initiated';
}
}
}
session_start();
$tmp = new CDice();
echo $tmp->Roll();
echo $tmp->Roll();
echo $tmp->currentScore();
?>
Also not assigning an "initalial" value to a variable before trying to add things to it with +=, -=, etc causes PHP to throw a warning.

php global variable and instance variable utilization

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;

PHP function in a function

I am trying to build a function that will call another function.
For example, if I have an array full of function names to call, is it possible to call a function for every array value without writing it in a script?
Example:
function email($val=NULL) {
if($val)
$this->_email = $val;
else
return $this->_email;
}
function fname($val=NULL) {
if($val)
$this->_fname = $val;
else
return $this->_fname;
}
For email, fname, etc.
But I want to have it like:
function contr_val($key,$val) {
function $key($val=NULL) {
if($val)
$this->_$key = $val;
else
return $this->_$key;
}
function $key($val="hallo");
}
And call it with:
contr_val("email", "test")
You're really trying to create member variables dynamically and retrieve their values. This is what __get() and __set() are for.
Here's how you could use it:
class TestClass {
var $data = array();
public function __set($n, $v) { $this->data[$n] = $v; }
public function __get($n) {
return (isset($this->data[$n]) ? $this->data[$n] : null);
}
public function contr_val($k, $v = NULL) {
if ($v)
$this->$k = $v;
else
return $this->$k;
}
};
$sherp = new TestClass;
$sherp->contr_val("Herp", "Derp");
echo "Herp is: " . $sherp->contr_val("Herp") . "\n";
echo "Narp is: " . $sherp->contr_val("Narp") . "\n";
Something like this:
/*
Input: $val - any value
$varname - the variable name, for instance: _email
*/
function checkValue($val=NULL, $varname) {
if($val)
$this->$var = $val;
else
return $this->$var;
}
checkValue("hello", "_email");
checkValue("hello2", "_name");
If you are doing this for a class, consider using PHP's magic methods __get() and
__set().
In an array full of function names, this calls every function that exists.
ghoti#pc:~$ cat functest.php
#!/usr/local/bin/php
<?php
function one() { print "one\n"; }
function two() { print "two\n"; }
function three() { print "three\n"; }
$a=array( "one", "two", "three", "four" );
foreach ($a as $item) {
if (function_exists($item)) {
$item();
} else {
print "No such function: $item\n";
}
}
ghoti#pc:~$ ./functest.php
one
two
three
No such function: four
ghoti#pc:~$
You need to check if the function exists or not:
function contr_val($key,$val) {
if (!function_exists($key)) {
function $key($val=NULL) {
if ($val)
$this->_$key = $val;
}
}
else {
return $this->_$key;
}
}

Categories