PHP Private Variable issue - php

I try to get value of a private variable (limit), but I get the following error:
Fatal error: Uncaught Error: Using $this when not in object context in /home/vagrant/Code/wp/wp-content/plugins/StorePress/app/library/Pagination.php on line 36
My Class:
class Pagination
{
private $limit = 0;
private $limit_start = 0;
private $total = 0;
/**
* Generate Pagination for Products
* #param $pagination
* #return string
*/
public function __constructor($pagination = null)
{
$this->limit = $pagination['limit'];
$this->lim_start = ($pagination['start']) ?: null;
$this->total = $pagination['total'];
}
public function generatePagination()
{
echo $this->limit;
}
Here, I'm trying to print "$this->limit", a private variable, but it's not allowed to print the value that are assigned by the "__constructor".
Is there anything wrong in my code or is there any other solution to get that value?

I think, that the problem is in your OOP construction. You cannot echo $this private variable, when you don't create class object as first. So the solution might be:
class Pagination
{
private $limit = 0;
private $limit_start = 0;
private $total = 0;
/**
* Generate Pagination for Products
* #param $pagination
* #return string
*/
public function __constructor($pagination = null)
{
$this->limit = $pagination['limit'];
$this->lim_start = ($pagination['start']) ?: null;
$this->total = $pagination['total'];
}
public function generatePagination()
{
return $this->limit;
}
and then in your code, where you need to echo the limit value, you can use:
$pagination = new Pagination();
echo $pagination->generatePagination();
At first line, you will create new Pagination() object and in the second line, you will return the $limit value from your generatePagination class function.

Shouldn't your keyword __constructor be __construct instead according to this link

Related

Error found on simple php code, "Parsing error" [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 3 years ago.
Parse error: syntax error, unexpected 'public' (T_PUBLIC), expecting end of file in C:\xampp\htdocs\example.php on line 9
I'm getting this error, but can't see nothing wrong with the code.
What did I wrong? Won't return the expected results.
The program is supposed to show: echo $myorder->OrderTotal();
<?php
class CartEntry
{
//changing to private
private $Price;
private $Quantity;
}
//Adding functions to get price and quantity,
public function __construct($Price, $Quantity)
{
$this->Price = $Price;
$this->Quantity = $Quantity;
}
public function ReturnPrice() {
return $this->Price;
}
public function ReturnQuantity() {
return $this->Quantity;
}
}
//
class CartContents
{
//Changed to private
private $items = array();
}
//Adding function to return items, same as above
public function __construct($items) {
$this->items = $items;
}
public function ReturnItems() {
return $this->items;
}
}
class Order
{
private $cart;
private $salesTax;
//cartcontents function removed
function __construct( float $salesTax, Array $items){
$this->salesTax = $salesTax;
$this->items = $items;
}
function OrderTotal()
{
$cartTotal = 0;
for ($i = 0; $i < count($this->items); $i++) {
$cartTotal += $this->items[$i]->Price * $this->items[$i]->Quantity;
}
$cartTotal += $cartTotal * $this->salesTax;
return $cartTotal;
}
}
$entry1 = new CartEntry();
$entry1->Price = 1.2;
$entry1->Quantity = 120;
$entry2 = new CartEntry();
$entry2->Price = 2.2;
$entry2->Quantity = 200;
$mycart = new CartContents();
$mycart->items = array($entry1, $entry2);
$items = $mycart->ReturnItems();
$mytax = 0.2;
//Items variable can be changed with mycart
$myorder = new Order($items, $mytax);
echo $myorder->OrderTotal();
?>
Here is the corrected code:
<?php
class CartEntry
{
//changing to private
private $Price;
private $Quantity;
public function __construct($Price, $Quantity)
{
$this->Price = $Price;
$this->Quantity = $Quantity;
}
public function ReturnPrice() {
return $this->Price;
}
public function ReturnQuantity() {
return $this->Quantity;
}
}// end class
class CartContents
{
//Changed to private
private $items = array();
public function __construct($items) {
$this->items = $items;
}
public function ReturnItems() {
return $this->items;
}
} // end class
class Order
{
private $cart;
private $salesTax;
function __construct( float $salesTax, Array $items){
$this->salesTax = $salesTax;
$this->items = $items;
}
function OrderTotal()
{
$cartTotal = 0;
for ($i=0, $max=count($this->items); $i < $max; $i++) {
$cartTotal += $this->items[$i]->ReturnPrice() * $this->items[$i]->ReturnQuantity();
}
$cartTotal += $cartTotal * $this->salesTax;
return $cartTotal;
}
}
$entry1 = new CartEntry(1.2, 120);
$entry2 = new CartEntry(2.2,200);
$mycart = new CartContents([$entry1,$entry2]);
$items = $mycart->ReturnItems();
$mytax = 0.2;
//Items variable can be changed with mycart
$myorder = new Order($mytax,$items);
echo $myorder->OrderTotal();
See live code.
One should avoid putting a brace after declaring class properties if the class has methods; that's what caused the error message that the OP encountered. As per the online Manual:
... class definitions begin with the keyword class, followed by a
class name, followed by a pair of curly braces which enclose the
definitions of the properties and methods (emphasis mine) belonging to the class.
Don't let the term 'function' fool you. If it's in a class it is a method; see this discussion.
But after fixing that issue there were others.
If you are suppose to initialize properties in a constructor, then you need to pass in the correct parameters when you instantiate an object, instead of trying to set those properties as if they were public.
Note, also that when an object has methods for reading private properties then you need to use those methods instead of trying to access the private properties directly.
Lastly, I changed this line of code
for ($i=0; $i < count($this->items); $i++) which executes correctly but it is more efficient to count the items just once instead of doing it on every iteration, so I inserted instead:
for ($i=0, $max=count($this->items); $i < $max; $i++){
You should put all your methods inside the class. In your code, the class CartEntry only contains 2 private variables:
class CartEntry
{
//changing to private
private $Price;
private $Quantity;
}
Anything outside the class will be considered invalid.

Laravel Api only returns empty objects

I'm trying to return an object from my Laravel api routes, but all that's returned is an empty array.
My model looks like this:
class MobilePageStats extends Model
{
//
private $score;
private $mobileFriendly;
private $numberRobotedResources;
private $numberTransientFetchFailureResources;
private $transientFetchFailureUrls;
private $cms;
private $ruleResults;
/**
* MobilePageStats constructor.
* #param int $score
* #param bool $mobileFriendly
* #param int $numberRobotedResources
* #param int $numberTransientFetchFailureResources
* #param array $transientFetchFailureUrls
* #param string $cms
* #param array $ruleResults
*/
public function __construct(
$score,
$mobileFriendly,
$numberRobotedResources,
$numberTransientFetchFailureResources,
$transientFetchFailureUrls,
$cms,
$ruleResults
) {
$this->score = $score;
$this->mobileFriendly = $mobileFriendly;
$this->numberRobotedResources = $numberRobotedResources;
$this->numberTransientFetchFailureResources = $numberTransientFetchFailureResources;
$this->transientFetchFailureUrls = $transientFetchFailureUrls;
$this->cms = $cms;
$this->ruleResults = $ruleResults;
}
And I also got getters on everything.
I set all the data in my controller with the constructor, in this function:
public function getData() {
$cms = "";
$score = $this->data->ruleGroups->USABILITY->score;
$mobileFriendly = $this->data->ruleGroups->USABILITY->pass;
if(isset($this->data->pageStats->numberRobotedResources)){
$numberRobotedResources = $this->data->pageStats->numberRobotedResources;
}else{
$numberRobotedResources = '';
}
if(isset($this->data->pageStats->numberTransientFetchFailureResources)){
$numberTransientFetchFailureResources = $this->data->pageStats->numberTransientFetchFailureResources;
}else{
$numberTransientFetchFailureResources = '';
}
if(isset($this->data->pageStats->transientFetchFailureUrls)){
$transientFetchFailureUrls = $this->data->pageStats->transientFetchFailureUrls;
}else{
$transientFetchFailureUrls = '';
}
if(isset($this->data->pageStats->cms)){
$cms = $this->data->pageStats->cms;
if($cms != 'WORDPRESS' && $cms != 'JOOMLA'){
$cms = $this->checkCMS();
}
}
$cvp = $this->getConfigureViewport();
$fontSizes = $this->getUseLegibleFontSizes();
$avoidPlugins = $this->getAvoidPlugins();
$sizeToViewport = $this->getSizeContentToViewport();
$tapTargets = $this->getSizeTapTargetsAppropriately();
$ruleResults = [$cvp, $fontSizes, $avoidPlugins, $sizeToViewport, $tapTargets];
$mobilePageStats = new MobilePageStats($score, $mobileFriendly, $numberRobotedResources,
$numberTransientFetchFailureResources, $transientFetchFailureUrls, $cms, $ruleResults);
return $mobilePageStats;
}
In my API routes I then try to return the model like this:
Route::get('/mobilePageSpeed', function(Request $request){
$data = new PageSpeedMobileController($request->url);
return response($data->getData());
});
But all I get returned when I make the request is:
<body>
<pre style="word-wrap: break-word; white-space: pre-wrap;">[]</pre>
</body>
Why is the object not returned? I know it contains data, because I can print it. But can't send it?
I have tried both repsonse()->json($data->getData()); And json_encode($data->getData()), but they give me the same result? I just can't seem to find a solution that works.
So how do I return objects from Laravel Api?
The answer would be to json_encode every single object after you cast them to arrays. Should work :)
You override the original Model constructor with your version, the model is not filled with attributes nor booted.
I dunno what you want to achieve but if you extends a class from Eloquent\Model you cannot override is own costructor without calling the original one, i.e.:
public function __construct(array $attributes = [])
{
parent::__construct($attributes);

Notice: Undefined variable: cur_order in

I am getting an error : Notice: Undefined variable: cur_order in ,can anyone guide me where i am went wrong,below is my code:
<?php
class Products {
var $name;
var $description;
var $productId;
function Products($id = 0, $infoArr = array()) {
if ($id > 0 && count($infoArr)) {
$this->name = $infoArr['name'];
$this->description = $infoArr['description'];
$this->productId = $id;
}
}
/**
* #static
*/
function loadAllProducts() {
$arr = getProducts();
$prods = array();
foreach ($arr as $id=>$info) {
$prods[$id] = new Products($id,$info);
}
return $prods;
}
/**
* function loadOrderDetails
*
* This function should be giving us all the information about the order:
* The customer's name and address, the products that were ordered (deescriptions too) and the order totals.
* See products that php to see what is expected to be shown
*
* #param Integer $order_id the unique identifier for the order
* #return Array $cur_order the details of the order
*
*/
function loadOrderDetails($order_id) {
$orders = getOrderInfo();
$products = getProducts();
$customer = getCustomerInfo();
$address = getAddresses();
return $cur_order;
}
}
?>
$cur_order does not exist in your code. How can you return it?
function loadOrderDetails($order_id) {
$orders = getOrderInfo();
$products = getProducts();
$customer = getCustomerInfo();
$address = getAddresses();
return $cur_order; // <-- this variable does not exist
}
You can only return one of the four variables you have used in that method or any of the member variables of that class (although that wouldn't be relevant in this case).
Another observation, you pass $order_id as a parameter but never use it. Do you really need to have it be a parameter then?
In your function "loadOrderDetails" you are returning variable $cur_order. It doesn't look like you've defined this variable yet.
If you were to return $address it would probably work. Or within the function define $cur_order = "test"
You are returning the $cur_order variable inside the loadOrderDetails function but you have not declared it in the function.
Just use $cur_order = true;
If you need to load the variable from outside the function use global $cur_order;

Calling method on all instances of class

I am looking for a way to call a function on all instances of a class preferably via a static method call.
Example:
class number{
private $number;
static function addAll(){
//add all of the values from each instance together
}
function __construct($number){
$this->number = $number;
}
}
$one = new number(1);
$five = new number(5);
//Expecting $sum to be 6
$sum = number::addAll();
Any help on this would be greatly appreciated. Thanks!
It can be done like this:
class MyClass {
protected $number;
protected static $instances = array();
public function __construct($number) {
// store a reference of every created object
static::$instances [spl_object_hash($this)]= $this;
$this->number = $number;
}
public function __destruct() {
// don't forget to remove objects if they are destructed
unset(static::$instances [spl_object_hash($this)]);
}
/**
* Returns the number. Not necessary here, just because
* you asked for an object method call in the headline
* question.
*/
public function number() {
return $this->number;
}
/**
* Get's the sum from all instances
*/
public static function sumAll() {
$sum = 0;
// call function for each instance
foreach(static::$instances as $hash => $i) {
$sum += $i->number();
}
return $sum;
}
}

PHP foreach over an array of objects

I'm trying to use a foreach loop for an array of objects. Inside of the BeginBattle() method I want to iterate through all of the objects and increment their played count automatically. Unfortunately, the web browser shows I have an error: Fatal error: Call to a member function BattleInitiated() on a non-object in /nfs/c05/h01/mnt/70299/domains/munchkinparty.neededspace.net/html/Battle.php on line 75
Any ideas?
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of Battle
*
* #author joshualowry
*/
class Battle {
/**
*
* #var <type>
*/
private $_players;
/**
*
* #var <type>
*/
private $_battleInProgress;
/**
*
*/
public function Battle(){
$this->_players = array();
$this->_battleInProgress = FALSE;
}
/**
*
* #param <type> $player
* #return <type>
*/
public function AddPlayer($player){
if(!$this->_battleInProgress)
$this->_players[] = $player;
else
return;
//Spit some error
}
/**
*
* #param <type> $player
* #return <type>
*/
public function BattleWon($player){
if($player != NULL)
$player->BattleWon();
else
return;
//Spit some error
}
/** GetPlayerByName Get the player's object by the player's name field.
*
* #param <type> $playerName
* #return <type>
*/
public function GetPlayerByName($playerName){
foreach($this->_players as &$player) {
if($player->GetName() == $playerName)
return $player;
}
return NULL;
}
/**
*
*/
public function BeginBattle(){
$this->_battleInProgress = TRUE;
foreach($this->_players as $player){
$player->BattleInitiated();
}
}
/**
*
*/
public function DisplayCurrentBoard() {
echo "Name Alias Wins Battles<br/>";
foreach($this->_players as &$player){
echo "$player->GetName() $player->GetAlias() $player->GetWins() $player->GetBattles()<br/>";
}
}
}
?>
This is where everything is declared and called:
<?php
include 'Battle.php';
include 'Person.php';
include 'Player.php';
$currentBattle = new Battle();
$playerA = new Player("JohnnyDanger","John",0,0);
$playerB = new Player("JoshTheJest","Josh",0,0);
$PlayerC = new Player("CarbQueen","Nicole",0,0);
$currentBattle->AddPlayer($playerA);
$currentBattle->AddPlayer($playerB);
$currentBattle->AddPlayer($playerC);
$currentBattle->BeginBattle();
$currentBattle->BattleWon($currentBattle->GetPlayerByName("Josh"));
$currentBattle->DisplayCurrentBoard();
?>
The Player Class
<?php
/**
* Description of Player
*
* #author joshualowry
*/
class Player extends Person {
private $_alias;
private $_wins;
private $_battles;
public function Player($name, $alias, $wins, $battles) {
parent::SetName($name);
$this->_alias = $alias;
$this->_battles = $battles;
if($battles == 0) {
$this->_wins = 0;
}
else {
$this->_wins = $wins;
}
}
protected function SetAlias($value){
$this->_alias = $value;
}
public function GetAlias(){
return $this->_alias;
}
protected function SetBattles($value) {
$this->_battles = $value;
}
public function GetBattles(){
return $this->_battles;
}
protected function SetWins($value) {
$this->_wins = $value;
}
public function GetWins() {
return $this->_wins;
}
public function BattleWon(){
$this->_wins += 1;
}
public function BattleInitiated(){
$this->_battles += 1;
}
}
?>
The error message indicates that you are trying to all the BattleInitiated() method on something that wasn't an object.
Judging from your code, the problem seems to be with this loop, in the BeginBattle() method :
foreach($this->_players as $player){
$player->BattleInitiated();
}
Which means $player, at least one in your array, is probably not an object ; maybe it's null, or an array ?
To know more, you should use var_dump to display the content of $this->_players before the loop, just to make sure it contains what you expect it to :
public function BeginBattle(){
var_dump($this->_players);
$this->_battleInProgress = TRUE;
foreach($this->_players as $player){
$player->BattleInitiated();
}
}
If $this->_players doesn't contain what you expect it to (and it probably doesn't !), you'll then have to find out why...
Considering $this->_players is modified by the AddPlayer() method, which adds what it receives to the end of the array, I would bet that AddPlayer() is called at least once without a correct $player as a parameter.
To help with that, you could use var_dump on the $player being added :
public function AddPlayer($player){
var_dump($player);
if(!$this->_battleInProgress)
$this->_players[] = $player;
else
return;
//Spit some error
}
If that var_dump indicates at least once that $player is not an object (for instance, it's null, or an array, or a string, ...), that's the cause of your Fatal Error.
don't you see it??
it's all because of a small typo:
$playerA = new Player("JohnnyDanger","John",0,0);
$playerB = new Player("JoshTheJest","Josh",0,0);
$PlayerC = new Player("CarbQueen","Nicole",0,0);
$currentBattle->AddPlayer($playerA);
$currentBattle->AddPlayer($playerB);
$currentBattle->AddPlayer($playerC);
declared: $_P_layerC
used: $_p_layerC
correct that and you're good to go
Your $player variable is either null or not an Object of the type you want it to be.
PlayerObject is what ever your class name for player is.
For example
$battle=new Battle();
$player1=new PlayerObject();
$player2="player";
$battle->AddPlayer($player1);
$battle->AddPlayer($player2);
$battle->BeginBattle();
when you call BeginBattle() the $player1->BattleInitiated(); will be successful but the $player2->BattleInitiated() will give you the fatal error and stop your code from running. same if $player2 was null, an integer or something that is not PlayerObject.

Categories