Jump to content

Recommended Posts

Hi there, I am starting to learn OO PHP programming. After running math.php, it gives an output 'Use only numbers'.

Why? I don't understand this.

 

math.php

<?php
require('MathClass.php');
$c = new MathClass();
echo $c->add(5,10,15,20);
     
?>

 

MathClass.php

<?php

class MathClass{

function add(){
	$args = func_num_args();
	$sum = 0;
	$i = 0;

	for ($i ; $i < $args ; $i++){
		is_int(func_get_args($i)) ? $sum += func_get_args($i) : die('Use only numbers');
	}
	return $sum;
}
}
?>

class Math
{
    public function add() {
        return array_sum(array_filter(array_map('is_int', func_get_args())));
    }
}

 

(intval() would have worked too)

 

$math = new Math();
echo $math->add(1,2,3,4,5,'hello','world'); // Output: 15

 

Don't you just love PHP?

class MathClass{
function add(){
$numargs = func_num_args();
$args = func_get_args();
//echo  $args;
$sum = 0;$i = 0;
for ($i ; $i < $numargs ; $i++){

if(is_integer($i)) $sum += $args[$i];
//is_int(func_get_args($i)) ? $sum += func_get_args($i) : die('Use only numbers');

}
return $sum;
}
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.