PHP Access to Undeclared Static Property - php

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

Related

Error when printing how many levels are visible in tree in PHP

I am receiving the error "Using $this when not in object context". I think I might be using the class node incorrectly. I cannot figure out where I am going wrong at this point.
I am trying to get the answer 4 in the case of a tree like the below. This is because there are 4 visible layers.
$root = new TreeNode(8);
$root->left = new TreeNode(3);
$root->right = new TreeNode(10);
$root->left->left = new TreeNode(1);
$root->left->right = new TreeNode(6);
$root->left->right->left = new TreeNode(4);
$root->left->right->right = new TreeNode(7);
$root->right->right = new TreeNode(14);
$root->right->right->left = new TreeNode(13);
class TreeNode{
public $val;
public $left;
public $right;
public function __construct($val=0) {
$this->val = $val;
$this->left = NULL;
$this->right = NULL;
}
}
function findLeft($root){
$queue = $root;
while(!empty($queue)){
$size = sizeof($queue);
$i = 0;
$answer = 0;
while($i<$size){
$i= $i+1;
//if first node print
if ($i == 1){
$answer += 1;
}
if($this->left){
array_push($queue, $this->left);
}
if($this->right){
array_push($queue, $this->right);
}
array_unshift($queue); //shift first item
}
} return $queue;
}
//calling function
function visibleNodes($root) {
// Write your code here
if(empty($root)){
return 0;
} else {
$answer = findLeft($root);
}
return $answer;
}

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;

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.

PHP how can I find out right properties within Object

class a {
public $a = "3";
public $b = "0";
public $b = "3";
public $c = "0";
public $d = "0";
public $e = "0";
public $g = "0";
}
How can I find out which properties are greater than zero?
You can use the get_class_vars function outside the object itself like that:
$a = new a();
$class_vars = get_class_vars(get_class($a));
foreach ($class_vars as $name => $value) {
if ($value > 0) {
echo "$name : $value\n";
}
}
put this method inside your class and it will return all vars in array:
public function test() {
$vars = get_object_vars($this);
$r = array();
foreach($vars as $k => $v) {
if($v > 0){ $r[$k] = $v; }
}
return $r;
}

OOP in PHP - object array iteration

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/>";
}

Categories