I'm new to PHP OOP, but not so much to PHP, wanted to start learning.. and hit a few brick walls, but this one stumped me.. BUT since I can't find any questions anywhere on the web.. I can't find answers either..
So.. The Code.. I dumbed it down to its core problem, if I can understand that..
<?php
class wallet {
public $Money = 5;
public function Add($mMoney) {
$this->Money += $mMoney;
echo "added $mMoney to Wallet";
}
public function take($mMoney) {
$this->Money -= $nMoney;
}
public function check() {
echo $this->Money;
echo "Check?";
}
public function __get($var) {
echo "trying to get $var and Failing";
}
}
class person {
public $Name;
public $Wallet;
public $Purse;
public $Cash;
public function __construct($name, $cash) {
$this->Wallet = new wallet();
$this->Purse = new wallet();
$this->Name = $name;
$this->Cash = $cash;
}
public function status() {
echo "<br><table border = 1><tr><td>".$this->Name."</td><td> Wallet?</td><td> Purse </td></tr>
<tr><td> $ ".$this->Cash."</td><td>".$this->checkWallet()."<td>22</td></tr></table>";
}
public function toWallet($toAdd) {
$this->Wallet->add($toAdd);
}
public function checkWallet() {
echo $this->Wallet->check();
}
}
$bob = new person ("Bob", 10);
$sarah = new person ("Sarah", 20);
$bob->status();
$sarah->status();
$bob->toWallet(10);
$bob->status();
$sarah->status();
?>
Why won't toWallet Work? Why can't I access $this->checkWallet()..
The reason why ToWallet won't work is because the function thinks the echo from the Add is the return value. (Which is obviously a string and is useless in calculation). There needs to be a return command for the mMoney variable. Try typing something like this in the Add function
public function Add($mMoney) {
$this->Money += $mMoney;
echo "added $mMoney to Wallet";
return $mMoney;
}
I don't know how nobody else spotted that.
For Anyone who comes across this in the future.. Heres the Solution:
First: When you have an Object, don't echo or print the data to the screen, return it to the parent object to do that for you,
Second: Double check that all Variables are either function only i.e. $wallet, or are the objects variables $this->wallet because even though I was staring at the code for hours, I couldn't see that this was not the same variable..
new to OOP, what a mind-mess
Related
I am trying to make a singleton pattern but it seems I am making mistake somewhere. Everytime i try to create an instance from the class Cart it makes new one. Tested it with the setId() and getId() functions. It returns different number everytime.
class Cart
{
private $cartQuantity = 0;
private static $instance;
private $id;
private function __construct(){}
public function addQuantity($quantity){
$this->cartQuantity += $quantity;
}
public function getQuantity(){
return $this->cartQuantity;
}
public function setId(){
$this->id = rand(0, 10);
}
public function getId(){
return $this->id;
}
public static function startCount(){
if(self::$instance === null){
self::$instance = new Cart();
self::$instance->setId();
}
return self::$instance;
}
}
$inst = Cart::startCount();
echo $inst->getId();
What am I doing wrong? Seems like legit block of code to me :/ Thank you in advance!
Your singleton is working perfectly. I have tested it 10 times with the following code:
$inst = Cart::startCount();
echo $inst->getId();
$winst = Cart::startCount();
echo $inst->getId();
$ninst = Cart::startCount();
echo $ninst->getId();
$ninst->setId();
echo $ninst->getId();
echo $winst->getId();
$ginst = Cart::startCount();
echo $ginst->getId();
Results:
999444
555222
333999
333444
111111
222222
999999
888666
101010999
000777
If you change the ID, it keeps beeing changed. Otherwise always the same is returned. This is exactly what you should expect (note that rand(0,10)) also can deliver 10.
There is never more than one instance.
I cannot workout why this script always returns 0. If I change it to echo getSKU() it works, but Quantity, Price or Name never seems to work. If anybody has any ideas please, please help this is irritating the life out of me!
<?php
session_start();
$sku = "0001";
if (!isset($_SESSION[$sku])) {
$_SESSION[$sku] = new product($sku, 5);
} else {
}
echo $_SESSION[$sku]->getQuantity();
class product {
var $sku;
var $name;
var $price;
var $quantity;
function __construct($par1, $par2) {
$this->sku = $par1;
$this->quantity = $par2;
}
function setSKU($x) {
$this->sku = $x;
}
function getSKU() {
echo $this->sku;
}
function setName($x) {
$this->name = $x;
}
function getName() {
echo $this->name;
}
function setPrice($x) {
$this->price = $x;
}
function getPrice() {
echo $this->price;
}
function setQuantity($x) {
$this->quantity = $x;
}
function incrementQuantity() {
$this->quantity++;
}
function getQuantity() {
echo $this->quantity;
}
}
You should use return instead of echo. Your get...-methods currently don't return something (just implicitly null), they just echo the value you want to return.
To fix this, just replace in every get...-method echo with return - i.e.
function getQuantity() {
return $this->quantity;
}
In addition to that, you should know, that you cant store objects in $_SESSION (actually you could, but then you have to implement the magic __sleep and __wakeup-methods..).
You should think about other solutions to store your products inside the session (i.e. serialize them)
you shouldn't echo your attribute in get methodes
echo $this->Variable;
you should always return them.
return $this->Variable;
return returns program control to the calling module. Execution
resumes at the expression following the called module's invocation
for more information on return check the documentation here
while the issues brought up in the other answers should definitely be addressed, to answer your question i believe the quantity is probably not set. can you try adding this line?
$_SESSION[$sku]->setQuantity(5);
$_SESSION[$sku]->getQuantity();
I have this simple singleton class:
public static function getInstance() {
if (!self::$_controller) {
self::$_controller = new self();
}
return self::$_controller;
}
Using PHP 5.3, this code seems to work fine, but on PHP 5.2 it seems like the instance is not returned. I put in a simple debug message like so:
public static function getInstance() {
if (!self::$_controller) {
self::$_controller = new self();
echo "I seem to be working";
}
return self::$_controller;
}
But "I seem to be working" is never echoed out. What's going on here and how can I fix it?
The following is working at my end for PHP 5.3 and 5.2 both.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 0);
class SingleTon {
private static $_controller = null;
private function __construct() {
// do something here or leave it blank.
}
public static function getInstance() {
if (!self::$_controller) {
self::$_controller = new self();
echo "I seem to be working";
}
return self::$_controller;
}
}
$obj = SingleTon::getInstance();
echo "\n";
?>
It displays "I seem to be working". Let me know if you need any further assistance.
I have a strange problem. I am writing a callback-like system where some code calls a function in a class which adds the function to an array and then later on executes it. Here is my code:
class BaconClass {
private $array;
public function __construct() {
$this->array = array();
}
public function AddBacon($function) {
array_push($this->array, $function);
}
/* ... */
public function GetBacon() {
foreach($this->array as $function) {
echo $function();
}
}
}
Then I have some other code like this:
$bacon = new BaconClass();
$bacon->AddBacon(function() {
echo "Om nom nom";
});
/* And somewhere else I might have */
$bacon->AddBacon(function() {
echo "I like bacon";
});
/* And then after all of this I have */
$bacon->GetBacon();
This code will only print:
I like bacon
I have made sure that the array being passed to the AddBacon function is actually working, but whenever I use var_dump to see what is inside the array after I add an element to it, it always shows one object, which is always the latest one added.
Why is the code overwriting the previous element? If there is a better way to implement this code, I am open to suggestions.
What I have tried
I have tried using $this->array[] = $function, and I have also tried using $this->array[count($this->array)] = $function. Neither are working.
Just tested the provided code in php console, got this output;
class BaconClass {
private $array;
public function __construct() {
$this->array = array();
}
public function AddBacon($function) {
array_push($this->array, $function);
}
/* ... */
public function GetBacon() {
foreach($this->array as $function) {
echo $function();
}
}
}
$bc = new BaconClass();
$bc->AddBacon(function() {echo 'something'; });
$bc->AddBacon(function() {echo 'something else'; });
$bc->GetBacon();
// outputs: somethingsomething else
Seems to be working fine to me
I'm trying to use an interface as a substitute for the lack of enums in PHP, but it does not seem to be working the way I want it to.
Here is the code:
interface Brands
{
const abrand = "A Brand";
const anotherbrand = "Another Brand";
}
class Product
{
private $brand;
function __construct() {
}
public function getBrand() {
return Brands::$this->brand;
}
public function setBrand($value) {
$this->brand = $value;
}
}
$product = new Product();
$product->setBrand("aproduct");
echo $product->getBrand();
Can someone explain Why is the output is abrand instead of A Brand?
Well, that was stupid.
I should have been doing $product->setBrand(Brands::abrand); instead of $product->setBrand("aproduct");
:/