how can i get value from inside of function? - php

Is it possible to get those values inside of function and use those outside of function
here is my code:
<?
function expenditure () {
$totalexpenditure = $sum1 + $sum2;
}
function income () {
totalincome = $sum1 + $sum2;
}
$profit = $totalincome - $totalexpenditure;
?>
now my question is how can i get value of totalincome and toatalexpenditure ?
i am learning php alos new in php so please help me guys.

<?
function expenditure ($sum1, $sum2) {
$totalexpenditure = $sum1 + $sum2;
return $totalexpenditure;
}
function income ($sum1, $sum2) {
$totalincome = $sum1 + $sum2;
return $totalincome;
}
$profit = income ($sum1, $sum2) - expenditure($sum1, $sum2) ;
?>
return statement

Your code is wrong, because:
the variables within functions do not have value assigned (you should assign it preferably by function parameters, but another - working, but wrong - solution is making them global variables),
in the example given, $profit will be always 0 (zero).
The solutions are three:
Solution no. 1:
function expenditure ($sum1, $sum2) {
$expenditure = $sum1 + $sum2;
return $expenditure;
}
function income ($sum1, $sum2) {
$income = $sum1 + $sum2;
return $income;
}
And then you can use it like that:
$profit = income(10, 200) - expenditure(20,18);
Solution no. 2:
class Finances {
public $expenditure = 0;
public $income = 0;
public function addExpense($expense) {
$this->expenditure = $this->expenditure + $expense;
return $this;
}
public function addIncome($income) {
$this->income = $this->income + $income;
return $this;
}
public function getProfit() {
return $this->income - $this->expenditure;
}
}
and then you can use it like that:
$my_finances = new Finances();
$my_finances->addExpense(20)->addExpense(18)->addIncome(10)->addIncome(10);
$profit = $my_finances->getProfit();
Solution no. 3: (avoid using!)
function expenditure() {
global $sum1, $sum2;
return $sum1 + $sum2;
}
function income() {
global $sum1, $sum2;
return $sum1 + $sum2;
}
And then you use it like that:
$sum1 = 10;
$sum2 = 200;
$expenditure = expenditure();
$sum1 = 20;
$sum2 = 30;
$income = income();
$profit = $income - $expenditure;
I hope you see, why the Solution no. 3 is such a bad idea (as generally using global variables to pass something to function is bad idea).

This relates to another problem, that you may face at a later stage. What if you wanted to pass 2 variables in a function and change both their values.
$var1 = 22;
$var2 = 15;
function multi2(&$x, &$y){
$x = $x * 2;
$y = $y * 2;
}
multi2($var1, $var2);
print $var1 . ", " . $var2;
You will get this as an output
44, 30
The $x and $y parameters are not a variable themselves, but a reference (defined by &) to the variables passed through, this is helpful if you require to change the values external variables internally.
Link to understand more http://php.net/manual/en/language.references.pass.php

Related

How to predefine variable in function by using different variable?

I dont know how to predefine one of the variables in function.
<?php
$number = 3;
function test($num, $num2 = $number) {
$result = "num = ".$num." and num2 = ".$num2;
return $result;
}
echo test(1);
?>
It always prints out:
Fatal error: Constant expression contains invalid operations in C:\xampp\htdocs\php\index.php on line 3
It's better to use it like this:
function test($num, $num2 = 3) {/**/}
But, if you really need it, you can define a constant:
const NUMBER = 3;
function test($num, $num2 = NUMBER)
{
$result = "num = $num and num2 = $num2";
return $result;
}
echo test(1); // returns "num = 1 and num2 = 3"
And the 3d option, if you want to use some dynamic variable:
$number = 3;
function test($num, $num2)
{
$result = "num = $num and num2 = $num2";
return $result;
}
echo test(1, $number); // returns "num = 1 and num2 = 3"
Or you can use a class:
class Test
{
protected $number;
public function __construct($number)
{
$this->number = $number;
}
public function test($num)
{
$result = "num = $num and num2 = $this->number";
return $result;
}
}
$test = new Test(3);
echo $test->test(1); // returns "num = 1 and num2 = 3"
If you want assingn a default value to a param you must use a value (a constant expression) not a var (variable expression)
function test($num, $num2 = 3 )

Php function call from another function

I am trying to make a text game in PHP but i have problem since i am programing in php for few days. I need to call function attack (I need $_mainAttack since it is combination of $_baseAttack and special attack) from defend function so i can calculate the health loss I have placed -5 just to see if it is working..
Also in health i need attack to be able to lower hp so i could calculate the hp loss. My do while loop is wrong and i need help to make it functional. I want when health goes lower than 0 to exit the loop. When it exits the loop it will print game over. I am stuck in endless loop and i have no idea how to fix this.
This is index.php:
<?php
include 'Duel.php';
$duel = new Duel();
$duel->attack();
$duel->defend();
?>
This is my class duel:
<?php
class Duel{
public $_maxHealth = 20;
public $_currentHealth;
public $_baseAttack, $_specialAttack, $_mainAttack;
public $_specialChance, $deflectChance;
public $_defense;
function __construct()
{
echo 'begining of attack <br/>';
}
function attack()
{
$_specialChance = rand(0, 20);
$_specialAttack = 0;
if ($_specialChance < 10) {
$_specialAttack = 0;
} elseif ($_specialChance < 15) {
$_specialAttack = (int) rand(0, 5);
} elseif ($_specialChance <= 20) {
$_specialAttack = (int) rand(5, 10);
}
$_baseAttack = rand(1, 6);
$_mainAttack = $_baseAttack + $_specialAttack;
echo "Base attack is $_baseAttack: and special attack is : $_specialAttack attack is : $_mainAttack<br/>";
}
function defend()
{
$_maxHealth = 20;
do{
$deflectChance = rand(1, 10);
$deflect = 0;
if ($deflectChance < 5) {
$deflect = 0;
echo 'attack cannot be deflected';
}
elseif ($deflectChance > 5) {
$deflect = (int) rand(0, 3);
echo "attack is deflected for {$deflect} damage";
}
$_currentHealth = $_maxHealth + $deflect - 5;
echo "<br/>health is {$_currentHealth} <br/>";
}while($_currentHealth > 0);
if($_currentHealth > 0) echo "Game over";
}
} //end of class
You are always calculating $_currentHealth based on $_maxHealth, not the previous $_currentHealth.
Add before the loop:
$_currentHealth = $_maxHealth;
And change $_currentHealth = $_maxHealth + $deflect - 5; to:
$_currentHealth = $_currentHealth + $deflect - 5;
You can try returning the main attack variable from the attack function and simply call it on the defend function.
you are calculation $_mainAttack but doesn't subtract it from your health, therefore your player can't die and you end within an endless loop.

Memoizing fibonacci function in php

I've created a memoized function of the recursive version of fibonacci.
I use this as an example for other kinds of functions that would use memoization.
My implementation is bad since if I include it in a library, that means that the global variable is still seen..
This is the original recursive fibonacci function:
function fibonacci($n) {
if($n > 1) {
return fibonacci($n-1) + fibonacci($n-2);
}
return $n;
}
and I modified it to a memoized version:
$memo = array();
function fibonacciMemo($n) {
global $memo;
if(array_key_exists($n, $memo)) {
return $memo[$n];
}
else {
if($n > 1) {
$result = fibonacciMemo($n-1) + fibonacciMemo($n-2);
$memo[$n] = $result;
return $result;
}
return $n;
}
}
I purposely didn't use the iterative method in implementing fibonacci.
Is there any better ways to memoize fibonacci function in php? Can you suggest me better improvements? I've seen func_get_args() and call_user_func_array as another way but I can't seem to know what is better?
So my main question is: How can I memoize fibonacci function in php properly? or What is the best way in memoizing fibonacci function in php?
Well, Edd Mann shows an excellent way to implement a memoize function in php in His post
Here is the example code (actually taken from Edd Mann's post):
$memoize = function($func)
{
return function() use ($func)
{
static $cache = [];
$args = func_get_args();
$key = md5(serialize($args));
if ( ! isset($cache[$key])) {
$cache[$key] = call_user_func_array($func, $args);
}
return $cache[$key];
};
};
$fibonacci = $memoize(function($n) use (&$fibonacci)
{
return ($n < 2) ? $n : $fibonacci($n - 1) + $fibonacci($n - 2);
});
Notice that the global definition it's replaced thanks to function clousure and PHP's first-class function support.
Other solution:
You can create a class containing as static members: fibonnacciMemo and $memo. Notice that you don't longer have to use $memo as a global variable, so it won't give any conflict with other namespaces.
Here is the example:
class Fib{
//$memo and fibonacciMemo are static members
static $memo = array();
static function fibonacciMemo($n) {
if(array_key_exists($n, static::$memo)) {
return static::$memo[$n];
}
else {
if($n > 1) {
$result = static::fibonacciMemo($n-1) + static::fibonacciMemo($n-2);
static::$memo[$n] = $result;
return $result;
}
return $n;
}
}
}
//Using the same method by Edd Mann to benchmark
//the results
$start = microtime(true);
Fib::fibonacciMemo(10);
echo sprintf("%f\n", microtime(true) - $start);
//outputs 0.000249
$start = microtime(true);
Fib::fibonacciMemo(10);
echo sprintf("%f\n", microtime(true) - $start);
//outputs 0.000016 (now with memoized fibonacci)
//Cleaning $memo
Fib::$memo = array();
$start = microtime(true);
Fib::fibonacciMemo(10);
echo sprintf("%f\n", microtime(true) - $start);
//outputs 0.000203 (after 'cleaning' $memo)
Using this, you avoid the use of global and also the problem of cleaning the cache. Althought, $memo is not thread save and the keys stored are no hashed values.
Anyways, you can use all the php memoize utilites such as memoize-php
i think... this should to to memoize a fibonacci:
function fib($n, &$computed = array(0,1)) {
if (!array_key_exists($n,$computed)) {
$computed[$n] = fib($n-1, $computed) + fib($n-2, $computed);
}
return $computed[$n];
}
some test
$arr = array(0,1);
$start = microtime(true);
fib(10,$arr);
echo sprintf("%f\n", microtime(true) - $start);
//0.000068
$start = microtime(true);
fib(10,$arr);
echo sprintf("%f\n", microtime(true) - $start);
//0.000005
//Cleaning $arr
$arr = array(0,1);
$start = microtime(true);
fib(10,$arr);
echo sprintf("%f\n", microtime(true) - $start);
//0.000039
Another solution:
function fib($n, &$memo = []) {
if (array_key_exists($n,$memo)) {
return $memo[$n];
}
if ($n <=2 ){
return 1;
}
$memo[$n] = fib($n-1, $memo) + fib($n-2, $memo);
return $memo[$n];
}
Performance:
$start = microtime(true);
fib(100);
echo sprintf("%f\n", microtime(true) - $start);
// 0.000041
This's an implementation of memoize a fibonacci:
function fib(int $n, array &$memo = [0,1,1]) : float {
return $memo[$n] ?? $memo[$n] = fib($n-1, $memo) + fib($n-2, $memo);
}
Call
echo fib(20); // 6765
function fibMemo($n)
{
static $cache = [];
//print_r($cache);
if (!empty($cache[$n])) {
return $cache[$n];
} else {
if ($n < 2) {
return $n;
} else {
$p = fibMemo($n - 1) + fibMemo($n - 2);
$cache[$n] = $p;
return $p;
}
}
}
echo fibMemo(250);

adding arguments in a PHP

im very new to PHP and im hoping someone here could help me out. i need to write a class, an when the below page echos it, it will show the answers.
<?php
include_once('Math.php');
$Math = new _Math();
echo $Math->calculate(2,3,"+")."<br />";
echo $Math->calculate(2,3,"-")."<br />";
echo $Math->calculate(2,3,"*")."<br />";
echo $Math->calculate(9,3,"/")."<br />";
echo $Math->calculate(9,0,"/")."<br />";
echo $Math->calculate("3",3,"+")."<br />";
echo $Math->calculate(2.5,3,"+")."<br />";
echo $Math->calculate(3,3,"test")."<br />";
I thought the code below would work, but im getting nothing but a blank screen.
<?php
class _Math {
function calculate(2,3,"+"){
$x = 2 + 3;
return $x;
}
function calculate(2,3,"-"){
$x = 2 - 3;
return $x;
}
function calculate(2,3,"*"){
$x = 2 * 3;
return $x;
}
function calculate(9,3,"/"){
$x = 9 / 3;
return $x;
}
function calculate(9,0,"/"){
$x = 9 / 0;
return $x;
}
function calculate("3",3,"+"){
$x = "3"+3;
return $x;
}
function calculate(2.5,3,"+"){
$x = 2.5+3;
return $x;
}
function calculate(3,3,"test"){
$x = 3 test 3;
return $x;
}
Im hoping someone can point me in the right direction. Hopefully im not that far off. Thanks in advance.
Function arguments must be variables, not expressions, which is explained in the manual.
This is a partial implementation:
class _Math
{
function calculate($op1, $op2, $type)
{
switch ($type) {
case '+':
return $op1 + $op2;
case '-':
return $op1 - $op2;
// ...
}
}
}
Inside the function you write a switch that will return the result based on the $type argument.
You function should look like this
function calculate(num1, num2, operation){
switch(operation){
case '+':
return $num1 + $num2;
break;
case '*':
return $num1 * $num2;
break;
// continue here :)
}
}
You only need 1 function. and multiple function with the same name will throw an error in PHP.
This is not how you define functions. Im not even sure what youre trying to do.
The round brackets contain the parameters which you hand over to the function. So you call a function like that:
$Math->calculate(2,3,"+")
These last 3 things are the parameters. You have to define the function like this:
function calculate($x, $y, $operation){
//your code
}
You cannot define multiple functions with the same name, so you have to check the operation and calculate it depending on the input. For example, +
function calculate($x, $y, $operation){
if($operation === "+") {
return $x + $y;
}
}

Calling a function within a class

I am having trouble calling a specific function within a class. The call is made:
case "Mod10":
if (!validateCreditCard($fields[$field_name]))
$errors[] = $error_message;
break;
and the class code is:
class CreditCardValidationSolution {
var $CCVSNumber = '';
var $CCVSNumberLeft = '';
var $CCVSNumberRight = '';
var $CCVSType = '';
var $CCVSError = '';
function validateCreditCard($Number) {
$this->CCVSNumber = '';
$this->CCVSNumberLeft = '';
$this->CCVSNumberRight = '';
$this->CCVSType = '';
$this->CCVSError = '';
// Catch malformed input.
if (empty($Number) || !is_string($Number)) {
$this->CCVSError = $CCVSErrNumberString;
return FALSE;
}
// Ensure number doesn't overrun.
$Number = substr($Number, 0, 20);
// Remove non-numeric characters.
$this->CCVSNumber = preg_replace('/[^0-9]/', '', $Number);
// Set up variables.
$this->CCVSNumberLeft = substr($this->CCVSNumber, 0, 4);
$this->CCVSNumberRight = substr($this->CCVSNumber, -4);
$NumberLength = strlen($this->CCVSNumber);
$DoChecksum = 'Y';
// Mod10 checksum process...
if ($DoChecksum == 'Y') {
$Checksum = 0;
// Add even digits in even length strings or odd digits in odd length strings.
for ($Location = 1 - ($NumberLength % 2); $Location < $NumberLength; $Location += 2) {
$Checksum += substr($this->CCVSNumber, $Location, 1);
}
// Analyze odd digits in even length strings or even digits in odd length strings.
for ($Location = ($NumberLength % 2); $Location < $NumberLength; $Location += 2) {
$Digit = substr($this->CCVSNumber, $Location, 1) * 2;
if ($Digit < 10) {
$Checksum += $Digit;
} else {
$Checksum += $Digit - 9;
}
}
// Checksums not divisible by 10 are bad.
if ($Checksum % 10 != 0) {
$this->CCVSError = $CCVSErrChecksum;
return FALSE;
}
}
return TRUE;
}
}
When I run the application - I get the following message:
Fatal error: Call to undefined
function validateCreditCard() in
C:\xampp\htdocs\validation.php
on line 339
any ideas?
class Foo {
// How may I be called?
function bar() {
}
function baz() {
// Use $this-> to call methods within the same instance
$this->bar();
}
function eek() {
// Use self:: to call a function within the same class statically
self::bar();
}
}
// Use [class]:: to call a class function statically
Foo::bar();
// Use [object]-> to call methods of objects
$fooInstance = new Foo();
$fooInstance->bar();
Calling methods statically or as an instance method is not necessarily interchangeable, beware. That's all pretty well covered in the basics of OOP by the way.
Does the class containing the function within which you use the Switch-Case inherit the CreditCardValidationSolution Class....??
My guess would be that you are trying to call the function outside the class without inheriting it.... Maybe you just missed it....
Edit After Reading Comment :
What you need here is "Inheritance"
Take a look at the following links.....
http://www.killerphp.com/tutorials/object-oriented-php/php-objects-page-4.php
http://marakana.com/blog/examples/php-inheritance.html
Hope this helps....

Categories