Jump to content

[SOLVED] What am I doing wrong? (PHP OOP)


dbx

Recommended Posts

I'm trying to teach myself OOP, and it's not going well =)

 

Can someone tell me what is wrong with the following code?:

 

The class I created:

 

<?php

class numbersgame {

var $number;

function setNumber($num) {
	$this->number = $num;
	return;
}

function getNumber() {
	return $this->number;
}
}

?>

 

The page that uses it:

 

<?php

include("the_class.php");

$newgame = new numbersgame();

numbersgame::setNumber("3");

$res = $newgame->getNumber();

echo $res;

?>

 

Now, the way I see it... it should set number to "3" and display it on the page. At the moment, it doesn't display anything.

 

Why?  >:(

 

Thanks.

 

Link to comment
https://forums.phpfreaks.com/topic/136485-solved-what-am-i-doing-wrong-php-oop/
Share on other sites

1. Which version of PHP you use? Don't use PHP4 for OOP.

 

2.

include("the_class.php");

$newgame = new numbersgame();

$newgame->setNumber(3);

$res = $newgame->getNumber();

echo $res;

 

 

I am (was) using 4. My server supports PHP5 if I use the .php5 file extension.

 

I've renamed the files and changed that line of code, and it works!

 

Thanks for that.

This code is also PHP4.

<?php

class numbersgame {

   var $number;

   function setNumber($num) {
      $this->number = $num;
      return;
   }

   function getNumber() {
      return $this->number;
   }
}

?>

 

You should change it to PHP5

 

<?php

class numbersgame {

   private $number;

   public function setNumber($num) {
      $this->number = $num;
      return;
   }

   public function getNumber() {
      return $this->number;
   }
}

?>

 

Read more here

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.