I'm trying to build a function inside a PHP class, however whenever I invoke the function, I am only returning the first variable.
class Nums
{
private $a = 7;
private $b = 8;
public function sum()
{
return $this->a + $this->b;
}
public function __set($name,$value) {
switch($name) {
case 'a':
return $this->setA($value);
case 'b':
return $this->setB($value);
}
}
public function __get($name) {
switch($name) {
case 'a':
return $this->getA();
case 'b':
return $this->getB();
}
}
private function setA($i) {
$this->a = $i;
}
private function getA() {
return $this->$a;
}
private function setB($i) {
$this->b = $i;
}
private function getB() {
return $this->$b;
}
}
Am I doing something wrong here, because I can't really see what is wrong with this logic.
class Nums
{
private $a = 7;
private $b = 8;
public function sum()
{
return $this->a + $this->b;
}
}
$numObj = new Nums();
echo $numObj->sum();
Running this code returns 15 for me
It's working for me. Here's what i tried and it output 15
.
PHP CODE :
<?php
class Nums
{
private $a = 7;
private $b = 8;
public function sum()
{
return $this->a + $this->b;
}
}
$obj = new Nums();
$c = $obj->sum();
echo $c;
?>
OUTPUT :
15
<?php
class A
{
private $a = 7;
private $b = 8;
public function sum()
{
return $this->a + $this->b;
}
}
$obj = new A();
$c = $obj->sum();
echo $c;
?>