Steve Steve - 24 days ago 4
PHP Question

How do i call function in php

I have this simple php code.I am basically new with core php and i've used some frameworks before where the function is called through the url.

<?php
class calculation
{
public $x=5; $y=6;
public function getSum()
{
$z=$x+$y;
print_r($z);
}
}


How can i call
getSum()
function? I've tried with:

int main()
{
calcuation c1;
c1.getSum();
return 0;
}

Answer

Your code is not PHP code.

To call a method from an instance of object you have to do it like this :

$c1 = new calculation();
$c1->getSum();

See PHP OOP basics to learn more.

Be aware that your calculation class is wrong. To access class property, you have to use $this-> like this :

<?php
class calculation
{
    public $x=5; 
    public $y=6;

    public function getSum()
    {
        $z= $this->x + $this->y;
        //return $z; //would be a better way to do calculation
        print_r($z);
     }
}