OOP in PHP - object array iteration - php

I am trying to iterate through array of objects in PHP, but I can't figure it out. This is my code:
require_once("databaseConnect.php");
require_once("class/Ticket.php");
function showAll(){
$sql = "SELECT * FROM Ticket WHERE Status='1'";
$p = mysql_query($sql);
while ($row = mysql_fetch_object($p)){
$t = new Ticket($row->IDTicket, $row->IDUser, $row->TotalOdd, $row->PlacedBet, $row->PossibleWin, $row->Status, $row->Won, $row->Time);
$nizTiketa[] = $t;
}
return $nizTiketa;
}
$niz = showAll();
for ($i; $i<count($niz); $i++){
echo $niz[$i]->getIDTicket()."<br/>";
}
and this is class Ticket:
class Ticket {
private $IDTicket;
private $IDUser;
private $TotalOdd;
private $PlacedBet;
private $PossibleWin;
private $Status;
private $Won;
private $Time;
function Ticket($idTicket, $idUser, $totalOdd, $placedBet, $possibleWin, $status, $won, $time) {
$this->IDTicket = $idTicket;
$this->IDUser = $idUser;
$this->TotalOdd = $totalOdd;
$this->PlacedBet = $placedBet;
$this->PossibleWin = $possibleWin;
$this->Status = $status;
$this->Won = $won;
$this->Time = $time;
}
function getIDTicket(){
return $this->IDTicket;
}
function setIDTicket($idTicket){
$this->IDTicket = $idTicket;
}
.
.
.
I got error Call to a member function getIDTicket() on a non-object
How should it be done?

Couple of things I'd do here for sanity...
As mentioned by Joe, initialise your array before adding elements, eg
function showAll() {
$nizTiketa = array();
// ...
Either initialise your iteration counter $i to zero
for ($i = 0, $count = count($niz); $i < $count; $i++)
or more simply, use foreach
foreach ($niz as $ticket) {
echo $ticket->getIDTicket(), "<br/>";
}

Related

PHP catching excepion from another class in a loop

I'm total PHP newbie, learning while creating following app. I got stuck trying to catch exception which breaks the loop in class Basic. Exception comes from class ProductVariation. Function generateRandomItems should generate random items on base of class Product and product.json file and skip productVariation when color is null.
<?php
class Product implements Item
{
public $id;
public $name;
public $price;
public $quantity;
public function __construct($file)
{
if (!file_exists($file)) {
throw new Exception('ProductFileNotFound');
}
$data = file_get_contents($file);
$product = json_decode($data);
$id = $product->id;
$name = $product->name;
$price = $product->price;
$quantity = $product->quantity;
$this->id = $id;
$this->name = $name;
$this->price = $price;
$this->quantity = $quantity;
}
public function getAmount()
{
$this->amount = $this->price * $this->quantity;
return $this->amount;
}
public function __toString()
{
$output = '';
foreach ($this as $key => $val) {
$output .= $key . ': ' . $val . "<br>";
}
return $output;
}
public function getId()
{
return $this->id;
}
public function getNet($vat = 0.23)
{
return round($this->price / (1 + $vat), 2);
}
}
class ProductVariation extends Product
{
public $color;
public function __construct($file, $color)
{
parent::__construct($file);
$this->color = $color;
if (!is_string($color)) {
throw new Exception('UndefinedVariantColor');
}
return $this->color;
}
}
interface Item
{
public function getId();
public function getNet($vat);
}
class Products extends ArrayIterator
{
public function __construct($file, $color)
{
$this->product = new Product($file);
$this->productVariation = new ProductVariation($file, $color);
}
}
class Basic
{
public function generateRandomString($randomLength)
{
$characters = 'abcdefghijklmnopqrstuvwxyz';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $randomLength; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
public function generateRandomItems($length)
{
$colors = array(
"red", "green", "blue",
"white", "black", null,
);
$list = [];
for ($i = 2; $i < $length + 2; $i += 2) {
$color = $colors[array_rand($colors, 1)];
$products = new Products('product.json', $color);
$products->product->id = $i - 1;
$products->product->name = $this->generateRandomString(rand(3, 15));
$products->product->price = rand(99, 10000) / 100;
$products->product->quantity = rand(0, 99);
$products->productVariation->id = $i;
$products->productVariation->name = $this->generateRandomString(rand(3, 15));
$products->productVariation->price = rand(99, 10000) / 100;
$products->productVariation->quantity = rand(0, 99);
echo $products->product;
echo $products->productVariation;
array_push($list, $products->product, $products->productVariation);
}
$uid = uniqid();
$fp = fopen("products/" . $uid . '.json', 'w');
fwrite($fp, json_encode($list));
fclose($fp);
}
}
product.json file content is {"id":1,"name":"Produkt testowy","price":13.99,"quantity":19}
For one, the check should precede the assignment to check if it’s null (this is in your Basic class).
// put check first
if (!is_string($color)) {
throw new Exception('UndefinedVariantColor');
}
$this->color = $color;

Notice: Undefined variable: arr in /opt/lampp/htdocs/IRIS/controllers/get_category.php on line 9

I am trying to get access to a static variable from another class, but I keep getting an error (the one in the title) that says my variable is not being recognized.
Below is my Categorize class where the static variable, which is an array named $arr, is located:
class Categorize extends Controller{
public static $arr = array();
function run($xml){
global $FILE_ROOT, $STORAGE, $REQ_ID, $CMD_EXTRA, $LIB,
$BIN;
$numCategories = intval($xml->numCategories);
self::$arr;
/*self::$arr = array();*/
/*if(!pe($xml, "resourceList")) die(err("No resources found"));*/
for($i=0;$i < $numCategories; $i++){
$name = intval($xml->nameCat);
if($i=0){
$arr[0][0] = $name;
}else{
$arr[$i][0] = $name;
}
}
$j = 0;
while($j < $numCategories){
$numDoc = intval($xml->numDoc);
$k = 0;
foreach($xml->resourceList->resource as $res){
$arr[$j][$k] = $res;
$k++;
}
$j++;
}
$output = "Done!";
$response = "<parameters><requestType>categorize</requestType><requestID>". $REQ_ID . "</requestID><resourceList>". $output . "</resourceList></parameters>";
return $response;
}
}
Here is a class called Get_category where I am trying to access the static variable $arr from my the Categorize class:
class Get_category extends Controller{
function run($xml){
global $FILE_ROOT, $STORAGE, $REQ_ID, $CMD_EXTRA, $LIB,
$BIN;
include_once __DIR__.'/categorize.php';
$file = $xml->filename;
Categorize::$arr;
/*$arrlength = count($arr);*/
$arrlength = max(array_map('count', $arr));
$response = "<parameters>\n<requestID>" . $REQ_ID ."</requestID>\n<requestType>get_category</requestType>";
for($i = 0; $i < $arrlength; $i++){
$lengthcolumn = count($arr[$i]);
for($j = 0; $j < $lengthcolumn; $j++){
if($arr[$i][$j] == $file){
echo $arr[$i][$j];
$response .= "<resource><id>" . $arr[$i][$j] . "</id>";
$response .= "</resource>";
}
}
}
$response .= "</parameters>";
return $response;
}
}
I don't understand why my $arr variable is being unrecognized.
Looks like you forgot to assign $arr = Categorize::$arr;
Categorize::$arr;
/*$arrlength = count($arr);*/
$arrlength = max(array_map('count', $arr));
In PHP you can't access class properties using regular variable syntax. Static properties are accessed using self::$property, object properties are accessed using $this->property.
So where you have $arr it should be self::$arr. This change is needed in both functions that you posted. It doesn't cause an error in the first function because it's assigning to the variable rather than reading it, so it creates the variable as well. But I assume that the intent was to fill in the public static $arr property, which is not happening because it's being accessed incorrectly.
class Categorize extends Controller{
public static $arr = array();
function run($xml){
global $FILE_ROOT, $STORAGE, $REQ_ID, $CMD_EXTRA, $LIB,
$BIN;
$numCategories = intval($xml->numCategories);
self::$arr;
/*self::$arr = array();*/
/*if(!pe($xml, "resourceList")) die(err("No resources found"));*/
for($i=0;$i < $numCategories; $i++){
$name = intval($xml->nameCat);
if($i=0){
self::$arr[0][0] = $name;
}else{
self::$arr[$i][0] = $name;
}
}
$j = 0;
while($j < $numCategories){
$numDoc = intval($xml->numDoc);
$k = 0;
foreach($xml->resourceList->resource as $res){
self::$arr[$j][$k] = $res;
$k++;
}
$j++;
}
$output = "Done!";
$response = "<parameters><requestType>categorize</requestType><requestID>". $REQ_ID . "</requestID><resourceList>". $output . "</resourceList></parameters>";
return $response;
}
}
class Get_category extends Controller{
function run($xml){
global $FILE_ROOT, $STORAGE, $REQ_ID, $CMD_EXTRA, $LIB,
$BIN;
include_once __DIR__.'/categorize.php';
$file = $xml->filename;
/*self:$arrlength = count(self:$arr);*/
$arrlength = max(array_map('count', self::$arr));
$response = "<parameters>\n<requestID>" . $REQ_ID ."</requestID>\n<requestType>get_category</requestType>";
for($i = 0; $i < self::$arrlength; $i++){
$lengthcolumn = count(self::$arr[$i]);
for($j = 0; $j < $lengthcolumn; $j++){
if(self::$arr[$i][$j] == $file){
echo self::$arr[$i][$j];
$response .= "<resource><id>" . self::$arr[$i][$j] . "</id>";
$response .= "</resource>";
}
}
}
$response .= "</parameters>";
return $response;
}
}
This is a significant difference between PHP and some other OOP languages like C++ and Java. See Could not retrieve a property of class in PHP for my explanation of the rationale of this.

PHP stops execution when calling external function

When the following PHP script executes:
<?php
include "imageManager.php";
include "imageHandling/spritesheet.php";
include "updateWindow.php";
include_once "dbConnection.php";
class deleteSoftware{
private $conn;
private $tableName;
public function __construct($name){
//Database Connection
$this->connectDatabase();
//Delete the Icon from the image pool
$tempFileManagerObject = new fileManager();
$tempFileManagerObject->setSrc("../ICONS/");
$deletedImageName = $tempFileManagerObject->getImageNameFromSoftwareName($name);
$tempFileManagerObject->delete("../ICONS/", $deletedImageName);
$tempFileManagerObject->deleteImageRenaming($deletedImageName);
//Deleting the record from the database
$prio = $tempFileManagerObject->getPriorityFromSoftwareName($name);
$subCategory = $tempFileManagerObject->getSubCategoryFromSoftwareName($name);
$this->tableName = $subCategory;
$this->conn->query("delete from ".$subCategory." where priority=".$prio);
$this->decrementPriorityInTable($prio);
//Delete from updateWindow if exist
$updateObject = new updateWindow();
$updateObject->deleteUpdate($name);
//Making sprite Sheet and moving to home directory
echo "step-0";
$spriteSheetObject = new spriteSheet(18, 18, 5, "../ICONS/", "../");
echo "step-1";
for ($x = 1; $x <= $spriteSheetObject->getImageCount(); $x++){ $tempFileManagerObject->copy("../ICONS/", "../Processing/", $x); }
echo "step-3";
$spriteSheetObject->setImagesFolder("../Processing/");
echo "step-4";
$spriteSheetObject->setOutPutFolder("../");
$spriteSheetObject->processSpriteSheet();
$spriteSheetObject->processSpriteSheetCss($this->getTotalSoftwaresCount());
for ($x = 1; $x <= $spriteSheetObject->getImageCount(); $x++){ $tempFileManagerObject->delete("../Processing/",$x); }
$tempFileManagerObject->setSrc("../Processing/");
$tempFileManagerObject->setDes("../");
$tempFileManagerObject->rename("tempArea", "home");
$tempFileManagerObject->move("../Processing/", "../", "home");
}
public function connectDataBase(){
$temp = new dbConnection();
$this->conn = $temp->connectDb();
}
public function getTheImageNameOfNewlyInsertedIcon($subCategory, $pri){
//First of all calculate the iconName of newly inserted image
//-Get the total number of rows for each subCategory table and add it untill we reach at the subCategory table where software to be inserted (Not add subCategory table rows count)
//- RowCounts + maxPriority in that table + 1
//- If there is already software for
//Calculating the total number of rows upto subCateogryTable excluding the subCategoryTable and then add up
$temp = false;
$rowCount = 0;
$this->tableName;
$this->conn->query("use windows");
$softwareTable = $this->conn->query("select * from software order by priority");
foreach ( $softwareTable as $row ) {
$categoryTable = $this->conn->query("select * from ".$row["tableName"]." order by priority");
foreach ( $categoryTable as $row2 ) {
$subCategoryTable = $this->conn->query("select * from ".$row2["tableName"]." order by priority");
if (!strcmp($row2["category"], $subCategory)){
$this->tableName = $row2["tableName"];
$temp = true;
break;
}
$rowCount = $subCategoryTable->rowCount() + $rowCount;
}
if ($temp){break;}
}
$rowCount = $pri + $rowCount;
return $rowCount;//This will be the name of the image
//Navigate to Tables
//According to priority set the iconName
//Record the iconName please
//Insert the record in table
//Execute the spritesheet
//make css
//finally iterate the whole database and send a string
}
public function decrementPriorityInTable($pri){
$this->conn->query("use windows");
$softwareTable = $this->conn->query("select * from ".$this->tableName." order by priority");
foreach ( $softwareTable as $row ) {
if($row["priority"] >= $pri+1){
$this->conn->query("update ".$this->tableName." set priority=".($row["priority"]-1)." where priority=".$row["priority"]);
}
}
}
public function getTotalSoftwaresCount(){
$softwareCount = 0;
$softwareTable = $this->conn->query("select * from software order by priority");
foreach ( $softwareTable as $row ) {
$categoryTable = $this->conn->query("select * from ".$row["tableName"]." order by priority");
foreach ( $categoryTable as $row2 ) {
$subCategoryTable = $this->conn->query("select * from ".$row2["tableName"]." order by priority");
foreach ($subCategoryTable as $row3){
$softwareCount++;
}
}
}
$softwareCount++;
return $softwareCount;
}
}
?>
The line $spriteSheetObject = new spriteSheet(18, 18, 5, "../ICONS/", "../"); stops executions without any error.
The spriteSheet class comes from this library:
<?php
require("lib/WideImage.php");
//All the images size must first be set to be placed on canvas
//Depends on only 1-Image "canvasArea.jpg"
//image processing folder is by default a "imagesToBeProcessed"
//output folder is empty by default
class spriteSheet{
private $canvasWidth;
private $canvasHeight;
private $eachImageWidth;
private $eachImageHeight;
private $imagesFolder = "";
private $outputFolder = "";
private $imageCount = 0;
private $maxImageInARow;
function __construct($imgW=43,$imgH=43, $maxInRow=5, $src, $des){
$this->imagesFolder = $src;
$this->outputFolder = $des;
$this->imageCounter();
$this->eachImageWidth = $imgW;
$this->eachImageHeight = $imgH;
$this->canvasWidth = $imgW * $maxInRow;
$this->canvasHeight = $imgH * ceil($this->imageCount/$maxInRow);
$this->maxImageInARow = $maxInRow;
}
public function setImagesFolder($src){
$this->imagesFolder = $src;
}
public function setOutPutFolder($des){
$this->outputFolder = $des;
}
public function imageCounter( ){
for ($x=1; true; $x++){
if (!file_exists($this->imagesFolder.$x.".jpg") and !file_exists($this->imagesFolder.$x.".png") and !file_exists($this->imagesFolder.$x.".gif")){
$this->imageCount = $x;
break;
}
}
$this->imageCount--;
}
public function setCanvasSize( ){
$canvas = WideImage::load($this->imagesFolder."canvasArea.jpg")->resize($this->canvasWidth, $this->canvasHeight, "fill");
$canvas->saveToFile($this->imagesFolder."tempArea.jpg");
}
public function resizeAllIcons( ){
$loopEnable = true;
for ($x=1; $loopEnable == true; $x++){
if (file_exists($this->imagesFolder.$x.".jpg")){
$iconImage = WideImage::load($this->imagesFolder.$x.".jpg")->resize($this->eachImageWidth, $this->eachImageHeight, "fill");
$iconImage->saveToFile($this->imagesFolder.$x.".jpg");
}
else if (file_exists($this->imagesFolder.$x.".png")){
$iconImage = WideImage::load($this->imagesFolder.$x.".png")->resize($this->eachImageWidth, $this->eachImageHeight, "fill");
$iconImage->saveToFile($this->imagesFolder.$x.".png");
}
else if (file_exists($this->imagesFolder.$x.".gif")){
$iconImage = WideImage::load($this->imagesFolder.$x.".gif")->resize($this->eachImageWidth, $this->eachImageHeight, "fill");
$iconImage->saveToFile($this->imagesFolder.$x.".gif");
}
else{
$loopEnable = false;
}
}
}
public function processSpriteSheet( ){
$this->resizeAllIcons();
$this->setCanvasSize();
$row=0; $col=0; $tempImageCounter = 1;
while ($tempImageCounter<=$this->imageCount){
$icon;
if (file_exists($this->imagesFolder.$tempImageCounter.".jpg")){
$icon = WideImage::load($this->imagesFolder.$tempImageCounter.'.jpg');
}
else if (file_exists($this->imagesFolder.$tempImageCounter.".png")){
$icon = WideImage::load($this->imagesFolder.$tempImageCounter.'.png');
}
else if (file_exists($this->imagesFolder.$tempImageCounter.".gif")){
$icon = WideImage::load($this->imagesFolder.$tempImageCounter.'.gif');
}
else{
break;
}
$canvas = WideImage::load($this->imagesFolder."tempArea.jpg");
$canvas->merge($icon, $row*$this->eachImageWidth, $col*$this->eachImageHeight, 100)->saveToFile($this->imagesFolder."tempArea.jpg");
$tempImageCounter++;
$row++;
if ($row == $this->maxImageInARow){
$row=0;
$col++;
}
}
}
public function processSpriteSheetCss($maxImageCss){
echo "maxImage:".$maxImageCss;
$imgCommon = "img.common{
width: ".$this->eachImageWidth."px;
height: ".$this->eachImageHeight."px;
background-image:url(home.jpg);
}";
$imgS=""; $y=0; $tempImageCounter = 1;
for($x=0; $tempImageCounter<=$maxImageCss; $x++){
$imgS = $imgS."img.s".$tempImageCounter."{background-position:".-1*($x*$this->eachImageWidth)."px ".-1*($y*$this->eachImageHeight)."px;}";
if ($tempImageCounter%$this->maxImageInARow == 0){
$x = -1;
$y++;
}
$tempImageCounter++;
}
echo "SpriteSheetCSS".$imgS;
$handle = fopen( "../css/sprite.css", "w" );
fwrite($handle, $imgS);
}
public function getImageCount(){
echo "total number of images-->".$this->imageCount;
return $this->imageCount;
}
}
?>
My script stops execution at that line without any error.
This file works perfectly on localhost but when I put this online and execute it then this problem happens.

PHP Access to Undeclared Static Property

I've made a class in PHP and I'm getting a Fatal Error(Title) on the line marked with an asterisk(*)
class monster{
private $id = 0;
private $name = "";
private $baseLevel = 0;
private $attack = 0;
private $defense = 0;
private $baseEXP = 0;
private $dropType = 0;
private $dropNum = 0;
function __construct($a, $b, $c, $d, $e, $f, $g, $h){
* self::$id=$a;
self::$name = $b;
self::$baseLevel = $c;
self::$attack = $d;
self::$defense = $e;
self::$baseEXP = $f;
self::$dropType = $g;
self::$dropNum = $h;
}
}
I can't figure out what's causing it, also, the following class(same file) is returning the same error.
class item{
private $id = 0;
private $name = "";
private $type = 0; #0-weapon, 1-armor, 2-charm, 3-ability
private $ability = 0;
private $desc = "";
private $cost = 0;
function __construct($a, $b, $c, $d, $e, $f){
self::$id=$a;
self::$name=$b;
self::$type=$c;
self::$ability=$d;
self::$desc=$e;
self::$cost = $f;
}
}
Do you happen to know what's causing the error or how I can fix it?
You should declare your properties with keyword static, e.g.
private static $id = 0;
Use $this-> instead of self::
Self is for static members and $this is for instance variables.
I did something like this
class A
{
static $A_TYPE = 'xxxx';
//....
// $this->type = 'xxxx'
public function getStringType()
{
return get_class($this)::${$this->type};
}
//.....
print A::$A_TYPE;
// xxxx

PHP Simple object oriented application

I am getting undefined variable for periods and subPeriods on the last line of this program. not sure what the problem is. Could it be my instances?
This is my first proper attempt at oop in PHP so i am sure i am doing something wrong.
$global_periods = 5;
$global_subperiods = 2;
$questionslist = array("q_1_1", "q_1_2", "q_2_1", "q_2_2", "q_3_1", "q_4_1", "q_5_1");
class User {
public $userId;
public $periods = array();
public function __construct($number)
{
$this->userId = $number;
}
public function addPeriod($pno)
{
$periods[] = new Period($pno);
}
}
class Period {
public $periodNo;
public $subPeriods = array();
public function __construct($number)
{
$this->periodNo = $number;
}
public function addSubPeriod($spno)
{
$subPeriods[] = new SubPeriod($spno);
}
}
class SubPeriod {
public $SubPeriodNo;
public $answers = array();
public function __construct($number)
{
$this->SubPeriodNo = $number;
}
public function addAnswer($answer)
{
$answers[] = new Answer($answer);
}
}
class Question {
public $answer;
public function __construct($ans)
{
$this->answer = $ans;
}
public function getAnswer()
{
echo $answer;
}
}
$userlist = array();
$sql = 'SELECT user_ref FROM _survey_1_as GROUP BY user_ref ORDER BY user_ref ASC';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$userlist[] = new User($row['user_ref']);
}
for ($i = 0; $i >= count($userlist); $i++)
{
for ($x = 1; $x > $global_periods; $x++)
{
$userlist[i]->addPeriod($x);
for ($y = 1; $y > $global_subperiods; $y++)
{
$userlist[i]->$periods[x]->addSubPeriod($y);
foreach($questionslist as $aquestion)
{
$sql = 'SELECT ' . $questionNumber . ' FROM _survey_1_as WHERE user_ref = ' .
$i . ' AND answer_sub_period = ' . $y . ' AND answer_period = ' . $x .'';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$userlist[i]->$periods[x]->$subPeriods[y]->addAnswer($row[$questionNumber]);
}
}
}
}
}
$userlist[3]->$periods[2]->$subPeriods[2]->getAnswer();
Remove all the $ signs behind the $userlist, you only need to define the first variable. You can't use dollar signs like this, this way, it will try get the value of the word after the $ sign and call that, but that variable doesn't exist.

Categories