PHP Class Extends and Objects - php

I have a results.php and 2 classes, Dog which extends Pet class. The "fullDescription" method call is just returning null for the results (eg: "Description: Your pet is a named .")
What am I missing?
results.php:
<?php
//include('_includes/pet.class.php');
include("_includes/dog.class.php");
?>
<?php
// COLLECT THE VALUES FROM THE FORM
$petType = $_POST["petType"];
$petName = $_POST["petName"];
// CREATE A NEW INSTANCE OF THE CORRECT TYPE
if ($petType == "dog")
{
$myPet = new Dog();
$myPet->breed = Dog::randomBreed();
}
else
{
$myPet = new Cat();
$myPet->breed = randomBreed();
}
// ASSIGN THE VALUE FROM THE FORM TO THE name PROPERTY OF THE PET OBJECT
$myPet->name = $petName;
$myPet->descriptor = Pet::randomDescriptor();
$myPet->color = Pet::randomColor();
?>
<div class="basic-grey">
<h1>Here's the information about your pet:</h1>
<p>Pet Name: <?php echo $myPet->name; ?></p>
<p>Pet Name: <?php echo $myPet->breed; ?></p>
<p>Pet Name: <?php echo $myPet->color; ?></p>
<p>Pet Name: <?php echo $myPet->descriptor; ?></p>
<p>Description: <?php echo $myPet->fullDescription(); ?> </p>
Pet Class
<?php
class Pet
{
// DEFINE YOUR CLASS PROPERTIES HERE
private $name;
private $descriptor;
private $color;
private $breed;
///////// Getters Setters /////////
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setDescriptor($descriptor) {
$this->descriptor = $descriptor;
}
public function getDescriptor() {
return $this->descriptor;
}
public function setColor($color) {
$this->color = $color;
}
public function getColor() {
return $this->color;
}
public function setBreed($breed) {
$this->breed = $breed;
}
public function getBreed() {
return $this->breed;
}
// DEFINE YOUR METHODS HERE
public function fullDescription()
{
return "Your pet is a $this->descriptor $this->color $this->breed named $this->name.";
//echo $myPet->getName();
}
public static function randomDescriptor()
{
// SET UP AN ARRAY OF VALUES
$input = array("stinky", "huge", "tiny", "lazy", "lovable");
// RETURN A SINGLE RANDOM ELEMENT FROM THE ARRAY
return array_rand(array_flip($input), 1);
}
public static function randomColor()
{
// SET UP AN ARRAY OF VALUES
$input = array("tan", "brown", "black", "white", "spotted");
// RETURN A SINGLE RANDOM ELEMENT FROM THE ARRAY
return array_rand(array_flip($input), 1);
}
}
?>
Dog Class
<?php
include('pet.class.php');
//////////// DOG CLASS //////////////
class Dog extends Pet
{public static function randomBreed()
{
// SET UP AN ARRAY OF VALUES
$input = array("german shepherd", "dachsund", "retriever", "labradoodle", "bulldog");
// RETURN A SINGLE RANDOM ELEMENT FROM THE ARRAY
return array_rand(array_flip($input), 1);
}
}
?>

The problem is because of the following lines,
$myPet->breed = Dog::randomBreed();
and
$myPet->name = $petName;
$myPet->descriptor = Pet::randomDescriptor();
$myPet->color = Pet::randomColor();
You're trying to access private properities of class Pet. Plus, you didn't the assign property values using setter methods. The solution would be like this:
You cannot access private properties of a class from it's child class, or outside of the parent class. First declare them as protected properties:
class Pet
{
// DEFINE YOUR CLASS PROPERTIES HERE
protected $name;
protected $descriptor;
protected $color;
protected $breed;
// your code
}
and then on results.php page change those lines in the following way:
// your code
if ($petType == "dog")
{
$myPet = new Dog();
$myPet->setBreed(Dog::randomBreed());
}
else
{
$myPet = new Cat();
$myPet->setBreed(Cat::randomBreed());
}
$myPet->setName($petName);
$myPet->setDescriptor(Pet::randomDescriptor());
$myPet->setColor(Pet::randomColor());
echo $myPet->fullDescription();

In your Pet class you've set your properties to private which means they cannot be manipulated publicly (from within the application), and only from within the class in which they are set (Pet in this case). Any reason for that?
Set them to public:
public $name;
public $descriptor;
public $color;
public $breed;
Here's the manual on OOP visibility. Discusses the differences between public, protected, private.

Related

Fatal error after declaring function abstract

I have a problem with an error I am getting that says:
Class Car contains 1 abstract method and must therefore be decla
red abstract or implement the remaining methods (Car::accelerate) in C:\xampp
\htdocs\php\learn_php_oop\Car.php on line 58.
This is the code in two files I am using:
Car.php
<?php
/**
* represents generic properties and methods for any type of car
*/
class Car
{
protected $colour, $doorNumber, $fuelType, $rightHandDrive, $accelerate;
public function __construct($rightHandDrive = true)
{
$this->rightHandDrive = $rightHandDrive;
}
public function getColour()
{
return $this->colour;
}
public function setColour($colour)
{
$this->colour = $colour;
}
public function getDoorNumber()
{
return $this->doorNumber;
}
public function setDoorNumber($doorNumber)
{
$this->doorNumber = $doorNumber;
}
public function getFuelType()
{
return $this->fuelType;
}
public function setFuelType($fuelType)
{
$this->fuelType = $fuelType;
}
public function getRightHandDrive()
{
return $this->rightHandDrive;
}
public function setRightHandDrive($rightHandDrive)
{
$this->rightHandDrive = $rightHandDrive;
}
abstract protected function accelerate();
}
?>
Sport_car.php
<?php
include ('Car.php');
/**
* represents sport cars
*/
class Sport_car extends Car
{
public function accelerate()
{
$this->accelerate = 5;
}
}
?>
I have spent some time trying to figure out why this is happening but I just do not know why? Please help.
It's an OOP problem, in your case you must declare your Car Object as Abstract like this :
<?php
/**
* represents generic properties and methods for any type of car
*/
abstract class Car
{
protected $colour, $doorNumber, $fuelType, $rightHandDrive, $accelerate;
public function __construct($rightHandDrive = true)
{
$this->rightHandDrive = $rightHandDrive;
}
public function getColour()
{
return $this->colour;
}
public function setColour($colour)
{
$this->colour = $colour;
}
public function getDoorNumber()
{
return $this->doorNumber;
}
public function setDoorNumber($doorNumber)
{
$this->doorNumber = $doorNumber;
}
public function getFuelType()
{
return $this->fuelType;
}
public function setFuelType($fuelType)
{
$this->fuelType = $fuelType;
}
public function getRightHandDrive()
{
return $this->rightHandDrive;
}
public function setRightHandDrive($rightHandDrive)
{
$this->rightHandDrive = $rightHandDrive;
}
abstract protected function accelerate();
}
?>
Explanations :
A class wich is extended with at least one abstract method in it has to be defined as abstract itself, otherwise you'll get an error

Getting values from parent class to child class from an instance

I have a person class with a $name property and an officer class with an $officer_name property. I need to be able to get the $name property from the person class to the officer class. In this case it should have an output of "Major Blake". Do I need to make an instance of the officer class for me to be able to echo this out?
class person {
protected $name;
private function set_name($fv_name) {
$this->name = $fv_name;
}
public function get_name() {
return $this->name;
}
function __construct($fv_name) {
$this->set_name($fv_name);
}
}
class officer extends person {
private function give_rank(){
return "Major ";
}
function __construct() {
echo $officer_name = $this->give_rank() . parent::get_name();
}
}
$iv_person = new person("Blake");
Please try this code :
your class :
<?php
class person {
protected $name;
private function set_name($fv_name) {
$this->name = $fv_name;
}
public function get_name() {
return $this->name;
}
function __construct($fv_name) {
$this->set_name($fv_name);
}
}
class officer extends person {
private function give_rank(){
return "Major ";
}
function __construct($fv_name) {
parent::__construct($fv_name);
}
function output(){
return $this->give_rank().parent::get_name();
}
}
your call :
$iv_person = new officer("Blake");
echo $iv_person->output();

pass modified parent properties to child class

I created a parent class (A) and modified some of its public and protected properties.
I created a child class (B) that extends A.
I can see the parent properties at B instance after creating it.
Problem is: The inherited properties of B have the default values of A, from before I modified them.
I want B to hold the modified values of the inherited properties.
How?
class Dashboard {
protected $testBusinessesIds = '';
public function test_bids($a){
$this->testBusinessesIds = $a;
}
}
class DashboardDBHelper extends Dashboard{
protected $withoutTestBids = '';
public function __construct(){
if($this->testBusinessesIds != '')
$this->withoutTestBids = " AND B.`id`";
}
}
$d = new Dashboard();
$d->test_bids(23);
$dh = new DashboardDBHelper();
print_r($dh->withoutTestBids);
I see: '' instead of 'AND B.id'
You may need to put your property as static. Here's an example:
class A {
protected $value = 1;
protected static $staticValue = 1;
public function printStatic() {
self::$staticValue++;
echo self::$staticValue;
}
public function printNonStatic() {
$this->value++;
echo $this->value;
}
}
class B extends A {
public function printStatic() {
echo self::$staticValue;
}
public function printNonStatic() {
echo $this->value;
}
}
$a = new A();
$b = new B();
/* Class A */
$a->printStatic(); // 2
$a->printNonStatic(); // 2
/* Class B */
$b->printStatic(); // 2
$b->printNonStatic(); // 1
Static variables does not share the same class/object so if you modify the value it will be changed everywhere.

How get method from another class method

I have two class es
class Pet {
public $pet = null;
public function setPet(){}
public function getPet(){}
}
and
class B {
public $cat = 'cat';
public $dog = 'bog';
public function cat()
{
$pet = new Pet();
$pet->pet = $this->cat;
}
public function dog()
{
$pet = new Pet();
$pet->pet= $this->dog;
}
}
Can I get this:
$pet = new Pet();
$pet->setPet()->dog();
$pet->getPet(); //dog
I don't believe you can. You could make class B extends Pet. That will allow you to call the functions from the class Pet. Read up on object inheritance, that might help! http://php.net/manual/en/language.oop5.inheritance.php
You can simply extend Class Pet on Class B to call functions from the Pet class. So Class B inherits the functions of Pet.
Class B extends Pet {
// class B functions here...
}
I laughed while I'm writing down my code here..
<?php
class Pet {
public $name;
public function setName($string) {
$this->name = $string;
}
public function getName() {
return $this->name;
}
}
class Dog extends Pet {
public function bark() {
echo "Arf arf!";
}
}
class Cat extends Pet {
public function meow() {
echo "Meoooww~ purrr~";
}
}
$dog = new Dog();
$dog->setName("Jacob");
$dog->bark(); //Arf arf!
echo "Good job, ".$dog->getName()."!"; //Good job, Jacob!
?>
sir you cant call $pet->setPet()->dog() with ->dog() since setPet() is a function and not an object.. just like they said, the right thing to do with your code is to extend it as a super class and declare a Dog Class as the child class..
My variant
class Pet {
public $pet = null;
public function setPet($pet = null)
{
if (is_null($pet)) {
return new B($this);
} else {
$this->pet = $pet;
return $this;
}
}
public function getPet()
{
return $this->pet;
}
}
class B {
protected $pet = null;
protected $cat = 'cat';
protected $dog = 'bog';
public function __construct(Pet $pet)
{
$this->pet = $pet;
}
public function cat()
{
$this->pet->setPet($this->cat);
return $this->pet;
}
public function dog()
{
$this->pet->setPet($this->dog);
return $this->pet;
}
}
$pet = new Pet();
$pet->setPet()->cat();
var_dump($pet->getPet());

Use method of parent class when extending

Probably a silly question.. but how do I correctly use the methods of class Test in class Testb without overriding them?
<?php
class Test {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
<?php
class Testb extends Test {
public function __construct() {
parent::__construct($name);
}
}
<?php
include('test.php');
include('testb.php');
$a = new Test('John');
$b = new Testb('Batman');
echo $b->getName();
You need to give the Testb constructor a $name parameter too if you want to be able to initialize it with that argument. I modified your Testb class so that its constructor actually takes an argument. The way you currently have it, you should not be able to initialize your Testb class. I use the code as follows:
<?php
class Test {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class Testb extends Test {
// I added the $name parameter to this constructor as well
// before it was blank.
public function __construct($name) {
parent::__construct($name);
}
}
$a = new Test('John');
$b = new Testb('Batman');
echo $a->getName();
echo $b->getName();
?>
Perhaps you do not have error reporting enabled? In any event, you can verify my results here: http://ideone.com/MHP2oX

Categories