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;
}
}
Related
I am trying to make a simple while loop using a class to get the factorial of a number. However, for some reason, the while loop is only returning the value after it has run once.
Here is my code:
<?php
class Factorial {
public function calculate($int){
$intStep = $int-1;
do {
$int*=$intStep;
$int--;
return $int;
} while($int>0);
if (!is_int($int)){
echo "entry is not a number";
}
}
}
$factorial = new Factorial;
echo $factorial->calculate(5);
I see a number of problems with your code:
return $int; is run inside the do while loop, which means it'll only ever run once.
You're decrementing $int instead of $intStep
You're checking if $int is below zero instead of $intStep
Here's your code with all of these problems fixed, it works and returns 15:
class Factorial {
public function calculate ($int) {
if (!is_int($int)) {
echo "entry is not a number";
}
$intStep = $int - 1;
do {
$int += $intStep;
$intStep--;
} while ($intStep > 0);
return $int;
}
}
$factorial = new Factorial;
echo $factorial->calculate(5);
3v4l.org demo
You shouldn't return from your function until your result is ready. Since you return early, you won't finish your calculation.
In general, your life will be easier if you learn how to debug. For PHP, the easiest way would be to echo stuff throughout your code. If you put echo $int inside of your loop it would be more obvious to you what the issue was.
try this
<?php
class Factorial {
public function calculate($num){
$Factorial = 1;
$i =1;
do{
$Factorial *= $i;
$i++;
}while($i<=$num);
return $Factorial;
}
}
$factorial = new Factorial;
echo $factorial->calculate(5);
?>
Factorial ? Maybe the following code is what you want:
Don't forget negative Numbers.
class Factorial {
public function calculate ($int) {
if (!is_int($int)) {
echo "entry is not a number";
}
if ($int == 0 || $int == 1) {
$result = 1;
} else if ($int < 0) {
$result = $this->calculate($int + 1) * $int;
} else {
$result = $this->calculate($int - 1) * $int;
}
return $result;
}
}
$factorial = new Factorial;
echo $factorial->calculate(-4);
I have this code written but I am having little issue or might be I am missing something,
public function test()
{
$number = "8192";
for ($i=1; $i<=32; $i++)
{
if(($number % pow(2,$i)) == 0)
{
$final = 32-$i;
echo $final;
}
}
exit;
}
I need to get which Exponent aka $i is used and then need to minus the value from 32 (or something else) to get the final results.
Since you want to compare the values just change the if condition, the modulus operator will not give you the exact result,
Here is the complete answer :
public function test()
{
$number = "8192";
for ($i=1; $i<=32; $i++)
{
if($number == pow(2,$i))
{
$final = 32-$i;
echo $final;
break;
}
}
exit;
}
I am not understanding this ?quirk? of php at all... as I am looking over other peoples code I see that some people leave out the else statement completely and just place a "return false;" statement.
It seems this trick only works for the return statement and as you can see in the cases below it does not work when echoing text.
This is strange, take case two for example, surely this function is read proceeduraly, so the function will return "true" inside the if statement because the condition is met however when it leaves the if/else statement it should return FALSE because there is no ELSE statement. This DOES NOT happen and the function still returns true.
I can't make sense of this so hopefully someone can explain?
// Case 1
function checkNumber1($number) {
if ($number === 10) {
return true;
} else {
return false;
}
}
$number = 10;
var_dump(checkNumber1($number)); // Returns true
// Case 2
function checkNumber2($number) {
if ($number === 10) {
return true;
}
return false;
}
$number = 10;
echo '<br>';
var_dump(checkNumber2($number)); // Also returns true??
// Case 3
function checkNumber3($number) {
if ($number === 10) {
echo 'true' . '<br>';
} else {
echo 'false' . '<br>';
}
}
$number = 10;
echo '<br>';
checkNumber3($number); // Returns true
// Case 4
function checkNumber4($number) {
if ($number === 10) {
echo 'true' . '<br>';
}
echo 'false' . '<br>';
}
$number = 10;
checkNumber4($number); // Returns true and then false???
The return statement in a function immediately ends execution of the current function and returns control.
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
I wrote this:
$num1 = mt_rand(1,5);
$num2 = mt_rand(1,5);
$operators = array(
"+",
"-",
"*",
"/"
);
$result = $num1 . $operators[array_rand($operators)] . $num2;
(My best guess is) This doesn't work as I expected because in the array the operator is a string which makes everything a string:
var_dump($result);
Gives:
string(3) "4+3"
So my question would be how would you recommend approaching this* without changing the logic it too much?
Thanks in advance!!
*Making random operation among random numbers, and if possible, the operators should be stored in an array.
I have the feeling my title is not correctly describing the situation but I could not come up with a better idea, I'm open to suggestions :)
Of course, you could use eval to do this, but I certainly won't settle for such a solution.
I'd suggest defining a bunch of functions that take in two params and return a result, then use call_user_func_array on the result of array_rand.
function add($x, $y) { return $x + $y; }
function subtract($x, $y) { return $x - $y; }
function multiply($x, $y) { return $x * $y; }
function divide($x, $y) { return $x / $y; }
$operators = array('add', 'subtract', 'multiply', 'divide');
//...
$result = call_user_func_array($operators[array_rand($operators)], array($x, $y));
<?php
$num1 = mt_rand(1, 5);
$num2 = mt_rand(1, 5);
$operators = array(
"+",
"-",
"*",
"/"
);
switch ($operators[array_rand($operators)]) {
case "+":
$result = $num1 + $num2;
break;
case "-":
$result = $num1 - $num2;
break;
case "*":
$result = $num1 * $num2;
break;
case "/":
$result = $num1 / $num2;
break;
}
var_dump($result);
The clean solution would be to have a code branch for each operator, e.g.
function do_something($num1, $num2, $operator) {
switch ($operator) {
case '+':
return $num1 + $num2;
case '-':
return $num1 - $num2;
case '*':
return $num1 * $num2;
case '/':
return $num1 / $num2;
default:
throw new Exception('Unknown operator: '.$operator)
}
}
If you have more operators, you should create a map of operator => function and dynamically call the functions, for example:
$ftable = array(
'+' => 'fn_add',
'-' => 'fn_sub',
'*' => 'fn_mul',
'/' => 'fn_div'
);
function fn_add($a, $b) { return $a + $b; }
function fn_sub($a, $b) { return $a - $b; }
function fn_mul($a, $b) { return $a * $b; }
function fn_div($a, $b) { return $a / $b; }
function do_something($num1, $num2, $operator) {
global $ftable;
if (array_key_exists($operator, $ftable)) {
return call_user_func($ftable[$operator], $num1, $num2);
}
else {
throw new Exception('Unknown operator: '.$operator)
}
}
And of course, the unclean (slow, potentially dangerous) solution would be to use eval().
Create a function for each operation, then store operator => function name in an array.