penu
penu

Reputation: 1040

OOP member variable visibility

I have a few classes that extend "Shop", what's the best way to do this so that parent functions ie: list_items() can be used on child classes?

class Shop
{
   public function list_items() {
      foreach($wares as $w)
        echo $w;
   }
   public function buy($item){
   }
}

class Brewery extends Shop
{
   public $wares = array("Wine", "Beer", "Alcohol", "Sake", "Rum");
   public $keepers = array("Jack", "Jill", "Bob", "Sam");
}

function makeShop() //initialize a shop obj
{
  $s = new Brewery();
  $s->list_items(); //$wares is not visible!
}

Upvotes: 1

Views: 50

Answers (5)

thiago marini
thiago marini

Reputation: 544

$wares is not visible because it's not coming from anywhere.

Pass it as a function parameter or use it as a class member:

public function list_items($wares) {
  foreach($wares as $w)
    echo $w;
}

or:

class Shop
{
   public $wares = [];
   public function list_items() {
      foreach($this->wares as $w)
        echo $w;
   }
   public function buy($item){
   }
}

Upvotes: 1

Deano
Deano

Reputation: 176

When you extend a class you inherit all its functions. So just refer to them using $this->list_items() as you would any other class method.

Upvotes: 1

Elon Than
Elon Than

Reputation: 9765

$wares indeed is undefined because you should access it using $this->wares.

Also always limit visibility of methods and attributes to the maximum. Eg. here you can set it to protected.

Next thing is that you should stick with one naming convention. Using makeShop and list_items in one project is not good idea.

Upvotes: 1

Patricia
Patricia

Reputation: 2865

You can use all public and protected methods from Shop in the other classes.

Upvotes: 0

goldlife
goldlife

Reputation: 1989

use

$this

in foreach in your shop Class. $this is a keyword for non-static attributes or methods. with $this you can access all of your class attributes like public $wares. without $this you can't access your class attributes - this variable is unknown.

foreach($this->wares as $w)

and call your function makeshop() at the end of your script.:

makeshop();

So complete:

<?php
class Shop
{
   public function list_items() {
      foreach($this->wares as $w)
        echo $w;
   }
   public function buy($item){
   }
}

class Brewery extends Shop
{
   public $wares = array("Wine", "Beer", "Alcohol", "Sake", "Rum");
   public $keepers = array("Jack", "Jill", "Bob", "Sam");
}

function makeShop() //initialize a shop obj
{
  $s = new Brewery();
  $s->list_items(); //$wares is not visible!
}

makeshop();
?>

Upvotes: 1

Related Questions