A dummy class

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ngungo
Forum Commoner
Posts: 75
Joined: Thu Jun 08, 2006 10:45 pm

A dummy class

Post by ngungo »

What is wrong with this code? It does not output anything. Frustrated.

Code: Select all

<?php
class dummy {
   function dummy($one, $two) {
      $val = $one + $two;
      return $val;
   }
}
 
$i = 1;
$j = 2;
 
$x = new dummy($i, $j);
echo 'x = ' .$x;
?>
User avatar
EverLearning
Forum Contributor
Posts: 282
Joined: Sat Feb 23, 2008 3:49 am
Location: Niš, Serbia

Re: A dummy class

Post by EverLearning »

Constructors don't return values.

Read a little about classes - PHP Manual
ngungo
Forum Commoner
Posts: 75
Joined: Thu Jun 08, 2006 10:45 pm

Re: A dummy class

Post by ngungo »

Thanks!
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: A dummy class

Post by Christopher »

Code: Select all

<?php
class dummy {
   var $val = 0;
 
   function dummy($one, $two) {
      $this->val = $one + $two;
   }
 
   function show() {
      return $this->val;
   }
}
 
$x = new dummy(1, 2);
echo 'x = ' . $x->show();
?>
In PHP5

Code: Select all

<?php
class dummy {
   protected $val = 0;
 
   function __construct($one, $two) {
      $this->val = $one + $two;
   }
 
   function __toString() {
      return $this->val;
   }
}
 
$x = new dummy(1, 2);
echo 'x = ' . $x;
?>
(#10850)
ngungo
Forum Commoner
Posts: 75
Joined: Thu Jun 08, 2006 10:45 pm

Re: A dummy class

Post by ngungo »

I understand now. Thanks!
Thing is this article gave me misinformation:
See how you can pass arguments right inside of your "new dummy3()" call? That's what's special about this. Though it might seem rather pointless, this is great to use for functions you use repetitively and want to make calls to with fewer lines of code. "$sum" will now return 3 if you did "echo $sum" by the way.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: A dummy class

Post by Chris Corbyn »

That's bad. Mr Spoono is naughty! And I used to recommend spoono as a beginner's guide to OOP. I won't now :cry:
Post Reply