Forum Moderators: coopster

Message Too Old, No Replies

PHP OOP problems

confusing homework

         

Baruch Menachem

5:58 pm on Feb 7, 2010 (gmt 0)

10+ Year Member



The way the assignment is written, we have to test inside the constructor for errors as the new item is made. I think this is supposed to be bad practice, but it is the way the instructor wants it.

I tired setting up a variable outside the constructor that the setter methods could test against, but it seems that PHP method do not allow for use of variables out side of the the class scope. Is that right?

had to set up a setter method inside the class to set my variables, but it won't recognize my variables inside the class either.


I have a method that creates and then another method that tests. Is that wrong?


public function setVariety($variety)


{
$this->variety=array("road","mountain","hybrid","motorcross");

}

//set the kind of bike (Mountain, road, hybrid,motocross)
public function setType($type)
{
$type=strtolower($type);
if (in_array($type,$variety))
$this->type=$type;
else echo "The bike $type was not of the correct variety\n";

The way I see the set up for the problem, we are supposed to set up testers that are variable based.

It looks like this is not possible.

CyBerAliEn

4:43 pm on Feb 8, 2010 (gmt 0)

10+ Year Member



It looks like you are missing on some fundamentals.

Lets suppose your class is called "bikes". The following code demonstrates roughly how to do what you want:

class bikes
{
//***Setup Class Variables***
var $variety = array();
var $type = '';
//***Constructor***
public function bikes()
{
/*whatever needs to be done*/
}
//***Methods***
public function setType($type)
{
$this->type = $type;
}
public function getType($type)
{
return $this->type;
}
/*etc...*/
}


The key to the above is this:

Any variables of your class must be declared within the class! If you plan to use a 'type' for 'bike', then you must declare the variable as shown. Likewise, using or manipulating these values within the class's methods must be done via the "$this->varName" expression. Calling "$this->type" will get you the bike type (or set it), but calling "$type" will do nothing.

When you call just "$type", PHP will try to reference the variable 'type' within the scope of the method. Since the "type" you want is in the class, you have to call it from the scope of the class (ie: '$this->varName').

In my view, a method/function should perform a very specific purpose. "Traditionally" you will often see methods for "set" and "get" in a programming class; these are all fine. But as you become more experienced with PHP and web development, you'll begin to build more complex methods that to do more complex things (and which may require the use of other methods or other classes).