Jump to content

Basic Object Oriented script does not work


DimitriDV

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;
}
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.