On May 28, 4:36 pm, vinnie <centro.ga...@gmail.comwrote:
This is my first "class" algorithm: when i execute it, i get this
error:
<<Fatal error: Call to undefined function: sum() in d:\class.php on
line 20>>
what's wrong? The class has the function, so why it says undefined?
<?php
print("first time class");
class somma
{
var $uno=10;
var $due=15;
var $tre=15;
function sum($uno, $due, $tre)
{
$totale = $uno + $due + $tre;
return($totale);
}
function sum_2()
{
$totale = $this->sum($this->uno, $this->due, $this->tre);
return $totale;
}
}
$sum=sum(34,40);
print("$sum");
?>
When using objects, you have to "create" them using the "new" keyword.
So consider a class a demarcation of what makes up an object, with
references to that demarcation being stored in the $variable that was
used to create the object.
Consider:
<code>
<h4>Somma object test class</h4>
<p>Print a sum from the Somma class</p>
<pre>
<?php
class Somma {
var $totale = 0;
var $tre = 15;
// Php4 constructor, "makes" object and
// returns a reference to the object in
// memory, to be stored in the $variable
// that is = new Somma($uno, $due);
function Somma($uno, $due) {
$this->totale = $uno + $due + $this->tre;
}
}
// $variable stores reference to object in
// memory
$variable = new Somma(34,40);
echo $variable->totale . "\n\n";
// Let's look at the object
print_r($variable);
?>
</pre>
</code>
Note the use of $this-and $variable in the different scopes ($this->
is used inside the class, $variable is used to refer to the object's
methods and properties, which are called $variable->Somma(85,98);