PHP class get method always returns 0 - php

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();

Related

PHP: Dynamically retrieving global variables

I am attempting to write a simple wrapper class to get the value of a global variable. I was thinking to use it like this:
print_r($class->session()->getAll());
print_r($class->cookie()->getAll());
Here's what I have:
class GlobalVars() {
private $current;
public function session() {
$this->current = 'SESSION';
return $this;
}
public function cookie() {
$this->current = 'COOKIE';
return $this;
}
public function getAll() {
return $_{$this->current}; // Obviously wrong
}
public function get($key) {
if (!isset($_{$this->current}[$key])) { // Obviously wrong
return false;
}
return $_{$this->current}[$key]; // Obviously wrong
}
public function set($arr) {
if (is_array($arr)) {
foreach ($arr as $k => $v) {
$_{$this->current}[$k] = $v;
}
}
}
}
$class = new GlobalVars();
print_r($class->session()->getAll());
With this example, I get a Notice: Undefined variable: _ message. What do I need to modify to get this to work?
In my opinion this is just a simple syntactical error you have made. What you did:
public function getAll() {
return $_{$this->current}; // Obviously wrong
}
But the correct way to emulate a variable from string is:
public function getAll() {
return ${"_".$this->current};
}
I have tested it. Similar behaviour for the other variables. More information on variable variables in the docs: http://php.net/manual/en/language.variables.variable.php
It's not gonna work like this. You need variable variables:
$var = "_{$this->current}";
var_dump($$var['rnd']);
Example
It's very bad way to use varVars, because it's not readable and usually IDE does not know what are you using and it's easy to get buggy code.

PHP T_OBJECT_OPERATOR | Variable Set

Working on a project of translating website and I had chose this solution
.
I'm trying to accomplish something like :
$VAR1 = $translate->__('Word_To_Translate');
This, not works for me since, the result is directly shown in stdout of the webpage. Even so when trying to call $VAR1 no result is returned.
This is not easily possible with the class you've mentioned.
If you wish to edit the class so it'll return the value instead of echoing it, you can edit class.translation.php, replace the two occurances of echo $str; with return $str;, and replace echo $this->lang[$this->language][$str]; with return $this->lang[$this->language][$str] (simply changing echo to return on both instances).
//$VAR1 delegating
$VAR1 = $translate->__('Word_To_Translate');
//class.translation.php
`class Translator {
private $language = 'en';
private $lang = array();
public function __construct($language){
$this->language = $language;
}
private function findString($str) {
if (array_key_exists($str, $this->lang[$this->language])) {
return $this->lang[$this->language][$str];
return;
}
return $str;
}
private function splitStrings($str) {
return explode('=',trim($str));
}
public function __($str) {
if (!array_key_exists($this->language, $this->lang)) {
if (file_exists($this->language.'.txt')) {
$strings = array_map(array($this,'splitStrings'),file($this->language.'.txt'));
foreach ($strings as $k => $v) {
$this->lang[$this->language][$v[0]] = $v[1];
}
return $this->findString($str);
}
else {
return $str;
}
}
else {
return $this->findString($str);
}
}
}`
Switched the echo for a return
Thank you very much uri2x && Rizier123.
For the moment looks that it is working solution.
Best wishes !

Another way to assign a function without executing it

Is there another way to assign or return a function without executing it? I think this is not the best solution ...
class Foo {
public function getDisplayFunction() {
return function() {
$this->display();
};
}
private function display() {
echo 'something';
}
}
$display = (new Foo())->getDisplayFunction();
//and execute it
$display();
I get it ... after trying 100 of things and 1 hour searching. Here my answer for all who looking also for the solution.
public function getDisplayFunction() {
return function() {
return $this->display();
}
}
is the same as:
public function getDisplayFunction() {
return [$this, 'display'];
}
the advantage is you don't have to pass args with this solution. That was the reason for the question.

Using array_push with closures overwriting previous element

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

PHP: Object in Object calling a Function

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

Categories