Jump to content

OOP Problem


3raser

Recommended Posts

You may see a lot of things wrong with the code below, but please bring it to my attention! I'm trying to advance my knowledge on OOP, but I'm trying my best to get the basics down. The below code, after selecting the two characters to fight, the page returns nothing, just blank. I'm pretty sure the error lyes within class_li.php, but I'm not exactly sure.

 

Script is attached.

 

[attachment deleted by admin]

Link to comment
Share on other sites

What have you done to debug what your code is doing?

 

If you check what execution path your code is taking when you submit the form, you will find that it is going to the main else{} statement which only outputs the "Character_xxx is not set.<br/>" when the corresponding character variable doesn't exist, but it does exist or you wouldn't have gotten to that else{} logic.

 

You need to fix your basic form handling logic to do what you want it to do when the form is submitted.

 

Link to comment
Share on other sites

What have you done to debug what your code is doing?

 

If you check what execution path your code is taking when you submit the form, you will find that it is going to the main else{} statement which only outputs the "Character_xxx is not set.<br/>" when the corresponding character variable doesn't exist, but it does exist or you wouldn't have gotten to that else{} logic.

 

You need to fix your basic form handling logic to do what you want it to do when the form is submitted.

 

When I submit the form, it goes to index.php, which is the correct path.

Link to comment
Share on other sites

EDIT: Error;  Fatal error: Class 'tiger' not found in C:\wamp\www\OOP\class_li.php on line 14

 

Fixed it, and code updated:

 

<?php
require_once('class_li.php');

$character_one = $_POST['character_one'];
$character_two = $_POST['character_two'];


if(!$character_one || !$character_two)
{
?>

<form action="index.php" method="POST">
<select name="character_one">
<option value="rabbit" selected="selected">Snake</option>
<option value="tiger">Tiger</option>
</select> vs
<select name="character_two">
<option value="wolf" selected="selected">Wolf</option>
<option value="eagle">Eagle</option>
</select>
<input type="submit" value="BATTLE!">
</form>

<?php
}
else
{
echo "succes";
$character_battle = new character_battle();
$character_battle->battle($character_one, $character_two);
}

 

Yet all I see is success, but nothing else. I'm thinking it may have to do with this block of code in class_li.php

 

class character_battle
{
public function battle($character_one, $character_two)
{	
	$character_one_class = new $character_one();
	$character_two_class = new $character_two();

	echo $character_one_class->description();
	echo $character_two_class->description();

	echo $character_one_class->attack($character_one_class->damage);
	echo $character_two_class->attack($character_two_class->damage);
}
}

Link to comment
Share on other sites

I don't see why we can't edit our previous posts, but anyways.....AGAIN...I did a lot of updates to the code, fixed more errors.

 

But for some reason, I get this error: Fatal error: Cannot access protected property rabbit::$damage in C:\wamp\www\OOP\class_li.php on line 20

 

I thought when a variable was protected, other classes could access it?

 

[attachment deleted by admin]

Link to comment
Share on other sites

Protected is only accessible to the class itself and it's siblings.

 

Thanks, I fixed all errors but one. For some reason, a wolf loses to an eagle, and so does a tiger. I mean, it has lower stats, so it should lose compared to tiger and wolf.

 

Newest download:

 

[attachment deleted by admin]

Link to comment
Share on other sites

$character_one_status + 1

 

should be:

 

$character_one_status += 1

 

This will solve your problem, but you are still far from writing true OOP. Every Object has methods, or behavior like we call them. In real-world we could define behavior as an action someone/something undertakes, like attacking.

 

interface Character {
    public function attacks(Character $c);
}

 

Here, I have defined that any Character can attack any Character (even itself: self-mutilation, suicide, ..).  And a method to make the Character actually take damage:

 

interface Character {
    public function attacks(Character $c);
    public function takeDamage($d);
}

 

To give your Character more of a real-world feel you could change attacks to punches.

 

interface Character {
    public function punches(Character $c);
    public function takeDamage($d);
}

 

The actual implementation of punches may look something similar to:

 

class Justin implements Character {
    public function punches(Character $c) {
        $c->takeDamage($this->_calculatePunchDamage());
    }
}


$justin = People::get('Justin');
$justin->punches(People::get('Bieber'));

Link to comment
Share on other sites

$character_one_status + 1

 

should be:

 

$character_one_status += 1

 

This will solve your problem, but you are still far from writing true OOP. Every Object has methods, or behavior like we call them. In real-world we could define behavior as an action someone/something undertakes, like attacking.

 

interface Character {
    public function attacks(Character $c);
}

 

Here, I have defined that any Character can attack any Character (even itself: self-mutilation, suicide, ..).  And a method to make the Character actually take damage:

 

interface Character {
    public function attacks(Character $c);
    public function takeDamage($d);
}

 

To give your Character more of a real-world feel you could change attacks to punches.

 

interface Character {
    public function punches(Character $c);
    public function takeDamage($d);
}

 

The actual implementation of punches may look something similar to:

 

class Justin implements Character {
    public function punches(Character $c) {
        $c->takeDamage($this->_calculatePunchDamage());
    }
}


$justin = People::get('Justin');
$justin->punches(People::get('Bieber'));

 

GAH! BIEBER?

 

Anyways, thanks for this! I'm still on my quest of learning OOP, and I actually understand most of what you just did. The only thing I'm a bit confused about is the get. Other than that, thanks!

 

I thought a format like this:

 

$variable = People::get($input);

 

Would be for static classes only. And do you mind if I ask, what does the get function do? Highly appreciated, thanks!

Link to comment
Share on other sites

get() in this scenario is a Factory method. Instead of writing new Justin() which would be weird, I can't spawn you. You were born, not spawned at a set age. So instead I retrieve you, like "Hey Justin, got a minute?" (except your reply is always: "Yeah, sure!")

 

Besides being less weird, it also makes your software flexible as it removes the hard dependency between Justin and your Object. Meaning you will only have to change the People class to return a different object when they call Justin instead of having to replace any and all occurences with the new class throughout your project.

 

GAH! BIEBER?

 

It was a joke :)

Link to comment
Share on other sites

get() in this scenario is a Factory method. Instead of writing new Justin() which would be weird, I can't spawn you. You were born, not spawned at a set age. So instead I retrieve you, like "Hey Justin, got a minute?" (except your reply is always: "Yeah, sure!")

 

Besides being less weird, it also makes your software flexible as it removes the hard dependency between Justin and your Object. Meaning you will only have to change the People class to return a different object when they call Justin instead of having to replace any and all occurences with the new class throughout your project.

 

GAH! BIEBER?

 

It was a joke :)

 

Ooh, thanks! And this wasn't a project, this was more of a test run. I'm starting my first ever actual OOP project. And I'd like some feedback, but this is currently the class_library.php:

 

<?php
/*
*	returnUsername is also used for checking if a user
*	is logged in, hence the name validation
*/

session_start();

class sql
{
private $grab;
public $return;
public $username;

public function connect($host, $user, $pass, $db)
{
	$error = array();

	mysql_connect($host, $user, $pass) or $error[0] = 1;
	mysql_select_db($db) or $error[1] = 1;

	if(!(empty($error[0])) || !(empty($error[1]))) die("MySQL configuration is wrong!");
}

public function returnAmount($query)
{
	$this->grab = mysql_fetch_assoc($query);

	if(mysql_num_rows($this->grab) < 1)
	{
		$this->return = "No results!";
		return $this->return;
	}
	else
	{
		$this->return = mysql_num_rows($this->grab($query));
		return $this->return;
	}
}
}

class validation
{
public function returnUsername()
{
	define('SESSION', $_SESSION['user']);

	if(!SESSION)
	{
		$username = null;
		return $username;
	}
	else
	{
		$username = SESSION;
		return $username;
	}
}
}

?>

Link to comment
Share on other sites

1) SQL is a bad name for a DB class, as DB is much broader then SQL. I could use a webservice as a database, or an XML file, or CSV, or ..

2) Keep in mind that more and more projects require to be able to connect to multiple databases, whether that being a SQL database or just flat-file.

3) Don't use die(), exit() or anything like that in your classes, learn Exception's and use them well

4) Don't tie business logic (returnAmount) to your DB, but to your Model's (User, Product, ..)

5) Don't use define() inside your classes, but use const instead. Use variables for dynamic values instead of resorting to store it in constants.

6) Validation is very broad and not reusable in any other projects. OO is about reusability, think of this while designing your objects.

Link to comment
Share on other sites

1) SQL is a bad name for a DB class, as DB is much broader then SQL. I could use a webservice as a database, or an XML file, or CSV, or ..

I don't really understand what you said here. I use a MySQL database. But are you suggesting to name it a database/XML file? Seems like XML is pointless over a database. But, other than that, I'm renaming my sql class to db.

 

2) Keep in mind that more and more projects require to be able to connect to multiple databases, whether that being a SQL database or just flat-file.

 

Hmm, I have absolutely no use for that in my current project. But I'll try to figure that in for the learning opportunity.

 

3) Don't use die(), exit() or anything like that in your classes, learn Exception's and use them well

 

Using google right now to search up some more information on exceptions, and hopefully find a good tutorial explaining them in detail.

4) Don't tie business logic (returnAmount) to your DB, but to your Model's (User, Product, ..)

 

I don't know what you mean by this. Creating returnAmount allows me to use re-use code that I will most likely have used quite a few times. So this lets me cut down the time to type it all over again.

 

5) Don't use define() inside your classes, but use const instead. Use variables for dynamic values instead of resorting to store it in constants.

 

As with the exceptions, I'm going to look up some more tutorials right away!

 

6) Validation is very broad and not reusable in any other projects. OO is about reusability, think of this while designing your objects.

 

Thats what returnAmount does. It allows me to re-use code that I will use quite a few times. For example, I tend to show how many people are registered, and how many people have submitted an application.

 

I'll post the new code soon!

 

Link to comment
Share on other sites

STILL NEED FEEDBACK >:D

 

New Code:

 

<?php
/*
*	returnUsername is also used for checking if a user
*	is logged in, hence the name validation
*/

session_start();

class db
{
private $grab;
public $return;
public $username;

public function connect($host, $user, $pass, $db)
{

	mysql_connect($host, $user, $pass) or throw new Exception('Incorrect DB settings.');
	mysql_select_db($db) or throw new Exception('DB connection failed.');

	try
	{

	} catch (Exception $e) {
		echo 'EXCEPTION FOUND: ' $e->getMessage();
	}

}

public function returnAmount($query)
{
	$this->grab = mysql_fetch_assoc($query);

	if(mysql_num_rows($this->grab) < 1)
	{
		$this->return = "No results!";
		return $this->return;
	}
	else
	{
		$this->return = mysql_num_rows($this->grab($query));
		return $this->return;
	}
}
}

class validation
{
public function returnUsername()
{
	define('SESSION', $_SESSION['user']);

	if(!SESSION)
	{
		$username = null;
		return $username;
	}
	else
	{
		$username = SESSION;
		return $username;
	}
}
}

?>

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.