Jump to content

oop classes & methods - why can i echo some and not others?


ricky spires

Recommended Posts

hello,

 

i have been following the php.net oop manual but im having a little trouble understanding something.

 

on this page in the manual: http://uk3.php.net/manual/en/language.oop5.basic.php

it shows this code and if i seperate it out i cant get it to echo the results i want. what am i doing wrong?

i have added a little extra code .

 

class Bear

class Bear {
    // define properties
    public $name;
    public $weight;
    public $age;
    public $sex;
    public $colour;

    // constructor
    public function __construct() {
       
                $this->name = "winny the poo";
	$this->weight = 100;
	$this->age = 0;
	$this->sex = "male";
	$this->colour = "brown";
    }

    // define methods

    public function eat($units) {
        echo $this->name." is eating ".$units." units of food... <br/>";
        $this->weight += $units;
    }

    public function run() {
        echo $this->name." is running... <br/>";
    }

    public function kill() {
        echo $this->name." is killing prey... <br/>";
    }

    public function sleep() {
        echo $this->name." is sleeping... <br/>";
    }


}

 

class PolarBear

class PolarBear extends Bear {

    // constructor
    public function __construct() {
        parent::__construct();
        $this->colour = "white";
        $this->weight = 600;
    }

function polarbar()
    {
        // Note: the next line will issue a warning if E_STRICT is enabled.
        Bear::bear();
    }

    // define methods
    public function swim() {
        echo $this->name." is swimming... ";
    }
}

 

 

now if i try to get back the results i have trouble.

 

this is fine

$bear = new Bear();

$bear->eat($units);
$bear->eat();
$bear->run();
$bear->kill();
$bear->sleep();

 

that echos back

//THE BEAR

winny the poo is eating 5 units of food...

winny the poo is eating units of food...

winny the poo is running...

winny the poo is killing prey...

winny the poo is sleeping...

 

//THE POLAR BEAR

winny the poo is eating 5 units of food...

winny the poo is eating units of food...

winny the poo is running...

winny the poo is killing prey...

winny the poo is sleeping...

winny the poo is swimming...

 

THAT FINE but how come i can echo out each of the properties?

why do these ways not work?

 

Bear::eat($units);
Bear::eat();
Bear::run();
Bear::kill();
Bear::sleep();

 

or

 

$bear = new Bear();
$bear->$name;
$bear->$weight;
$bear->$age;
$bear->$sex;
$bear->$colour;

 

or

 

echo Bear::eat($units);
echo Bear::eat();
echo Bear::run();
echo Bear::kill();
echo Bear::sleep();

 

or

 

$bear = new Bear();
echo $bear->$name;
echo $bear->$weight;
echo $bear->$age;
echo $bear->$sex;
echo $bear->$colour;

 

and the same goes for PolarBear

 

if i try and get back any of the properties on a page i get nothing ???

 

i even tried putting it in a loop and that didnt work

$bear = new Bear();

foreach ($bear as $bears){
echo $bears->$name;
echo $bears->$weight;
echo $bears->$age;
echo $bears->$sex;
echo $bears->$colour;
}

 

whats wrong.

why cant i get any results from these ?

thanks

Link to comment
Share on other sites

This:

 

function polarbar()
{
   // Note: the next line will issue a warning if E_STRICT is enabled.
   Bear::bear();
}

 

Is completely unnecessary.  You're already calling Bear's constructor in PolarBear's __construct() method.  What are you trying to do here?

 

As for the rest, your methods are not static, thus trying to invoke them with :: won't work.  Static methods are executed in class scope.  Calling Bear::eat($units) makes no sense because there's no object in play, so there's no $this variable to work with.  Read more: static

 

Now, to be absolutely clear, I'm NOT suggesting you turn your methods static.  Since static methods can be invoked anywhere simply by writing Class::method(/* args */), they are therefore global.  Globals are the antithesis of good OOP.

Link to comment
Share on other sites

SORRY, 1 more thing.

 

i see what you mean. I'm calling parent::__construct(); so it should work but if i remove

{
        // Note: the next line will issue a warning if E_STRICT is enabled.
        Bear::bear();
    }

 

from

 

// extended class definition
class PolarBear extends Bear {

    // constructor
    public function __construct() {
        parent::__construct();
        $this->colour = "white";
        $this->weight = 600;
    }

function polarbar()
    {
        // Note: the next line will issue a warning if E_STRICT is enabled.
        Bear::bear();
    }

    // define methods
    public function swim() {
        echo $this->name." is swimming... ";
    }



} //end class polarbear

 

i get no results at all. it breaks it some how ?

 

 

Link to comment
Share on other sites

<?php
class Bear {
    // define properties
protected $name;
    public $weight=100;
    public $age= 0;
    public $sex = "Male";
    public $colour= "Brown";
public $type = 'Brown Bear';

    // constructor
    function __construct($name) {       
        $this->name = $name;
    }

    // define methods

    public function eat($units) {
        echo $this->name." is eating ".$units." units of food... <br/>";
        $this->weight += $units;
    }

    public function run() {
        echo $this->name." is running... <br/>";
    }

    public function kill() {
        echo $this->name." is killing prey... <br/>";
    }

    public function sleep() {
        echo $this->name." is sleeping... <br/>";
	$this->age++;
    }

public function description() {
	$output = $this->name . ' is a ' . $this->type . ', with a beautiful ' . $this->colour . ' coat.';
	$output .= ($this->sex == 'Male') ? ' He ' : ' She ';
	$output .= 'is ' . $this->age . ' days old, and weighs in at ' . $this->weight . ' lbs.<br />';
	return $output;
}
}


class PolarBear extends Bear {

//if we make a constructor here, we will need to call the parent constructor if
//we want to set the name of the bear.  we of course could set it using $this, but 
//that would defeat the purpose of showing this.
function __construct($name) {
	parent::__construct($name);
	$this->colour = 'White';
	$this->type = 'Polar Bear';
}

    // define methods
    public function swim() {
        echo $this->name." is swimming... ";
    }
}

$bear = new Bear('Winney the Pooh'); //calling just the bear class.

$polar = new PolarBear('Snowman'); //calling the polar bear extension


$polar->eat(100);
$bear->eat(10);
$bear->sleep();

echo '<hr />' . $bear->description() . '<hr />' . $polar->description();

//using a foreach loop to look at the variables of the Polar Bear.
//you will notice that the name is not in there, that is because
//the name variable is protected. Changing it to public will make it appear here.
echo 'The polar bear is:';
foreach($polar as $var => $value) {
echo $var . ' is ' . $value . '<br />';
}

Link to comment
Share on other sites

Hello.

 

I am trying to get the same from a database but its not working. can any one see where im going wrong?

 

this is what is in my database

 

i created1 row in a db called bears =

 

id        = 1

name  = winney the poo

weight  = 100

age      = 0

sex      = male

colour  = brown

type      = brown bear

 

and i created 1 row in a db called polarbears =

 

id        = 1

colour  = white

type      = polar bear

 

 

 

i created a class called Bears

<?php
require_once(LIB_PATH.DS.'database.php');


class Bears {
  
protected static $table_name="bears";

protected static $db_fields = array(
'id',
'name',
'weight',
'age',
'sex',
'colour',
'type');


public $id;
public $name;
public $weight;
public $age;
public $sex;
public $colour;
public $type;


// "new" is a reserved word so we use "make"(or "build")
public static function make(

$id,
	$name="",
$weight="",
$age="",
$sex="",
$colour="",
$type="") {

	if(!empty($name)) {

		$kw = new Navigation();

		$kw->id = (int)$id;
		$kw->name = $name;
		$kw->weight = (int)$weight;
		$kw->age = (int)$age;
		$kw->sex = $sex;
		$kw->colour = $colour;
		$kw->type = $type;

		return $kw;
	}else{
		return false;
	}
} //end function make



    public function eat($units) {
        echo $this->name." is eating ".$units." units of food... <br/>";
        $this->weight += $units;
    }

    public function run() {
        echo $this->name." is running... <br/>";
    }

    public function kill() {
        echo $this->name." is killing prey... <br/>";
    }

    public function sleep() {
        echo $this->name." is sleeping... <br/>";
	$this->age++;
    }

public function description() {
	$output = $this->name . ' is a ' . $this->type . ', with a beautiful ' . $this->colour . ' coat.';

	$output .= ($this->sex == 'Male') ? ' He ' : ' She ';

	$output .= 'is ' . $this->age . ' days old, and weighs in at ' . $this->weight . ' lbs.<br />';
	return $output;
}



}

?>

 

 

and a class called PolarBears

 

<?PHP
require_once(LIB_PATH.DS.'database.php');

class PolarBears extends Bears {

    protected static $table_name="polarBears";

protected static $db_fields = array(
'id',
'colour',
'type');


public $id;
public $colour;
public $type;


// "new" is a reserved word so we use "make"(or "build")
public static function make(

$id,
$colour="",
$type="") {

	if(!empty($id)) {

		$kw = new Navigation();

		$kw->id = (int)$id;
		$kw->colour = $colour;
		$kw->type = $type;

		return $kw;
	}else{
		return false;
	}
} //end function make


    public function swim() {
        echo $this->name." is swimming... ";
    }

}

?>

 

this is the database class

 

please note that the database class was part of a tutorial i did.

 

<?PHP

require_once(LIB_PATH.DS."config.php");

class MySQLDatabase {

private $connection;
public $last_query;
private $magic_qoutes_active;
private $real_escape_string_exists;

function __construct() {
	$this->open_connection();	
	$this->magic_qoutes_active = get_magic_quotes_gpc();	
	$this->real_escape_string_exists = function_exists("mysql_real_escape_string");
}

public function open_connection(){
	$this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
	if(!$this->connection){
		die ('MySQL Datatbase Connection Failed: ' . mysql_error());
	} else {
		$db_select = mysql_select_db(DB_NAME, $this->connection);
		if (!$db_select) {
			die ('MySQL Datatbase Selection Failed: ' . mysql_error());
		}
	}
}

public function close_connection() {
	if(isset($this->connection)){
		mysql_close($this->connection);
		unset($this->connection);
	}
}

public function query($sql){
	$this->last_query = $sql;
	$result = mysql_query($sql, $this->connection);
	$this->confirm_query($result);
	return $result;
}

public function fetch_array($query){
	return mysql_fetch_array($query);
}

public function fetch_object($query){
	return mysql_fetch_object($query);
}

public function num_rows($query){
	return mysql_num_rows($query);
}	

public function insert_id(){
	return mysql_insert_id($this->connection);
}	

public function affected_rows(){
	return mysql_affected_rows($this->connection);
}	

public function escape_value($value){
	if ($this->real_escape_string_exists) {
		if ($this->magic_qoutes_active) { $value = stripslashes($value); }
		$value = mysql_real_escape_string($value);
	} else {
		if (!$this->magic_qoutes_active) { $value = addslashes($value); }
	}
	return $value;
}


private function confirm_query($result){
	if (!$result) {
		$output = "DATABASE.PHP - confirm_query = MySQL Datatbase Query Failed: " . mysql_error() . "<br><br>";
		$output .= "Last SQL query: " . $this->last_query;
		die($output);
	}
}

}

$database = new MySQLDatabase();
?>

 

 

 

 

im trying to get the data back on this page:

 

<?PHP
require_once("../includes/initialize.php");

$bears = new Bears(); //calling just the bear class.

$polars = new PolarBears(); //calling the polar bear extension


$polars->eat(100);
$bears->eat(10);
$bears->sleep();

echo '<hr />' . $bears->description() . '<hr />' . $polars->description();

echo 'The polar bear is:';
foreach($polars as $var => $value) {
echo $var . ' is ' . $value . '<br />';
}
?>

 

 

this is all it echos back

 

is eating 100 units of food...

is eating 10 units of food...

is sleeping...

is a , with a beautiful coat. She is 1 days old, and weighs in at 10 lbs.

is a , with a beautiful coat. She is days old, and weighs in at 100 lbs.

The polar bear is:id is

colour is

type is

name is

weight is 100

age is

sex is

 

 

thanks

 

p.s. should this be in a new thread ?

 

 

HANG ON ----

 

im not calling the db info any place..

 

i need to do something like this for each function i guess

 

public static function find_all(){
	global $database;
	$sql = "SELECT * FROM ".self::$table_name."";
	return self::find_by_sql($sql);
}

 

 

Link to comment
Share on other sites

ok. i made a little progress but is there a better way?

 

 

BEARS class

<?php
require_once(LIB_PATH.DS.'database.php');


class Bears {
  
protected static $table_name="bears";

protected static $db_fields = array(
'id',
'name',
'weight',
'age',
'sex',
'colour',
'type');


public $id;
public $name;
public $weight;
public $age;
public $sex;
public $colour;
public $type;


// "new" is a reserved word so we use "make"(or "build")
public static function make(

$id,
	$name="",
$weight="",
$age="",
$sex="",
$colour="",
$type="") {

	if(!empty($name)) {

		$kw = new Navigation();

		$kw->id = (int)$id;
		$kw->name = $name;
		$kw->weight = (int)$weight;
		$kw->age = (int)$age;
		$kw->sex = $sex;
		$kw->colour = $colour;
		$kw->type = $type;

		return $kw;
	}else{
		return false;
	}
} //end function make




    public function eat($units) {
$sql = "SELECT * FROM ".self::$table_name."";


        echo $this->name." is eating ".$units." units of food... <br/>";
        $this->weight += $units;
    }

    public function run() {
$sql = "SELECT * FROM ".self::$table_name."";

        echo $this->name." is running... <br/>";
    }

    public function kill() {
$sql = "SELECT * FROM ".self::$table_name."";

        echo $this->name." is killing prey... <br/>";
    }

    public function sleep() {
$sql = "SELECT * FROM ".self::$table_name."";

        echo $this->name." is sleeping... <br/>";
	$this->age++;
    }

public function description() {
$sql = "SELECT * FROM ".self::$table_name."";


	$output = $this->name . ' is a ' . $this->type . ', with a beautiful ' . $this->colour . ' coat.';

	$output .= ($this->sex == 'Male') ? ' He ' : ' She ';

	$output .= 'is ' . $this->age . ' days old, and weighs in at ' . $this->weight . ' lbs.<br />';
	return $output;
}



}

?>

 

 

POLARBEARS

<?PHP
require_once(LIB_PATH.DS.'database.php');

class PolarBears extends Bears {

    protected static $table_name="polarBears";

protected static $db_fields = array(
'id',
'colour',
'type');


public $id;
public $colour;
public $type;


// "new" is a reserved word so we use "make"(or "build")
public static function make(

$id,
$colour="",
$type="") {

	if(!empty($id)) {

		$kw = new Navigation();

		$kw->id = (int)$id;
		$kw->colour = $colour;
		$kw->type = $type;

		return $kw;
	}else{
		return false;
	}
} //end function make


    public function swim() {
$sql = "SELECT * FROM ".self::$table_name."";
        echo $this->name." is swimming... ";
    }

}

?>

 

NOW I GET:

Snowman is eating 100 units of food...

Winney the Pooh is eating 10 units of food...

Winney the Pooh is sleeping...

Winney the Pooh is a Brown Bear, with a beautiful Brown coat. He is 1 days old, and weighs in at 110 lbs.

Snowman is a Polar Bear, with a beautiful White coat. He is 0 days old, and weighs in at 200 lbs.

The polar bear is:weight is 200

age is 0

sex is Male

colour is White

type is Polar Bear

Link to comment
Share on other sites

please ignore the last post

 

ok. i made a little progress but is there a better way?

 

i thought it was working but i was looking at an old file, bears.php and not bears2.php so i got the results from before i tried pulling it from a db.

 

so, its still unsolved. How do i pull the bear class and the polar bear class from a db ??

my way didnt seem to work.

 

also, because im using function make() instead of the __construct where do i reference parent::__construct($name);  in the PolarBear class ?

 

function __construct($name) {

parent::__construct($name);

$this->colour = 'White';

$this->type = 'Polar Bear';

}

 

thanks :)

 

p.s sorry about the double post.I thought this should be in a new topic.

Link to comment
Share on other sites

I think you are getting a little confused on the way Objects work, and work together.  I would like to point you to a tutorial here,  Hopefully, this will answer all of your questions.

 

Remember that __construct() is called whenever an object is instantiated.  Using a function by any other name would mean it doesn't get called, unless you specifically call it.

Link to comment
Share on other sites

Thanks.

 

I'm definitely getting confused. All the tutorials on oop tell you how to do it without pulling the information from a database. then when i try pulling info from a database all code i learned before seems to go out the window.

 

Thanks for pointing me in the right direction. i really want to learn this way of coding.

 

THANKS :)

Link to comment
Share on other sites

Here's the thing: you shouldn't be building queries like this in your animals anyway.  The animals should be generated by another source, like an animal repository object, that would handle the business of mapping the animals to the db and vice-versa.

 

class AnimalRepository
{
   private $db; // <--- this is the database itself, likely a MySQLi or, even better, PDO object

   public function __construct($db) // <--- best to use Dependency Injection to wire up the db to the repo automatically
   {
      $this->db = $db;
   }

   // methods for retrieving, saving, etc. animals goes here
}

abstract class Animal
{
   // methods that ALL animals will have
}

class Bear extends Animal
{
   private $subspecies;

   public function __construct($subspecies)
   {
       $this->subspecies = $subspecies;
   }

   // Bear specific methods go here
}

/* Note no PolarBear class.  Unless PolarBears have unique behavior that's different than other bears 
    (and, really, they don't), there's no reason to subclass. */

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.