Initialising an array of objects - php

Program that tests the rand function is an example:
<?php
class number {
function number() {
$occurences=0;
}
public $occurences;
public $value;
}
$draws = 5000;
$numOfInts = 10;
//$integers = array();
$integers [] = new number();
//initialising loop
for($i=0;$i<=$numOfInts;$i++)
$integers[$i]->$value = $i; //debugger points here
for($i=0;$i<$draws;$i++) {
$integers[rand(0,numOfInts)]->$occurences++;
}
foreach($integers as $int)
printf("%5d %5d <br/>",$int->$value,$int->$occurences);
?>
Errors on the WAMP server:
Undefined variable: value in C:\path\index.php on line 31
Fatal error: Cannot access empty property in C:\path\index.php on line 31
What caused them and how to fix it? I suppose that the $integers is declared incorrectly.

You should access members of an object with this syntax:
$integers[$i]->value
$integers[$i]->occurences;
However you have to initialize your array first as well which means un-comment the initial line to
$integers = array();
As a matter of fact you are not using the better OOP style which would change your data structure like this:
class Number {
private $value;
private $occurences = 0;
public function __construct($value = 0) {
$this->value = $value;
}
public function getValue() {
return $this->number;
}
public function addOccurence() {
$this->occurences++;
}
public function getOccurences() {
return $this->occurences;
}
}
You would then access the members like this:
// init part
$integers = array();
for($i = 0; $i < $numOfInts; $i++) {
$integers[] = new Number($i);
}
// draws part
for($i=0; $i < $draws; $i++) {
$integers[rand(0,$numOfInts-1)]->addOccurence();
}
// print part
foreach($integers as $number) {
printf("%5d %5d<br />", $number->getValue(), $number->getOccurences());
}

Why?
//$integers = array();
$integers [] = new number();
Should just be
$integers = array();
for($i=0;$i<=$numOfInts;$i++) {
$integers[$i] = new number();
}
There are no typed arrays in PHP

Related

changing variable value outside a function inside a class

how can i make it change the count value. the RollingCurlX thing is a multithreading class for php which only let you process response through a function and i dont know how you should handle it. please help me
class MyClass extends RollingCurlX {
public function someFunc() {
$url = 'https://example.com/';
$count = 0;
function callback_functn($response, $url, $request_info, $user_data, $time) {
if ($response['c'] == 'd') {
$count++;
}
}
$RCX = new RollingCurlX(10);
for ($i=0; $i < 100; $i++) {
$post_data = ['a' => 'b'];
$RCX->addRequest($url, $post_data, 'callback_functn');
}
$RCX->execute();
echo $count;
}
}
$c = new MyClass();
$c->someFunc();
Use the use() declaration to give the function access to an external variable. Make it a reference with & so assignments to the variable inside the function will affect the outer variable.
function callback_functn($response, $url, $request_info, $user_data, $time) use (&$count) {
if ($response['c'] == 'd') {
$count++;
}
}
Try it
public function someFunc() {
$url = 'https://example.com/';
$count = 0;
$callbackFunction = static function ($response, $url, $request_info, $user_data, $time) use (&$count) {
if ($response['c'] == 'd') {
$count++;
}
};
$RCX = new RollingCurlX(10);
for ($i = 0; $i < 100; $i++) {
$post_data = ['a' => 'b'];
$RCX->addRequest($url, $post_data, $callbackFunction);
}
$RCX->execute();
echo $count;
}

PHP Variable Variables within setter function

I am trying to achieve a way to define an indefinite, but not infinite number of variables, to be used to create objects. I have tried a couple of ways to try this but i cant seem to wrap my head around this.
Here is what i came up with:
$aCount= 0;
$Foo = "Bar".$aCount;
$$Foo = array("Data1"=>NULL, "Data2"=>NULL);
function getBarData1() {
return ${$Foo}['Data1'];
}
function getBarData2() {
return ${$Foo}['Data2'];
}
function setBarData($newBarData1, $newBarData2) {
${$Foo}['Data1'] = $newBarData1;
${$Foo}['CONTENT'] = $newBarData2;
$aCount++;
}
setBarData('First', 'Line');
setBarData('Second', 'Dot');
setBarData('Third', 'Dash');
for($aCount == $aCount; $aCount > -1; $aCount--) {
echo getBarData1() ."\n";
echo getBarData2() ."\n";
}
Any help would be greatly appreciated.
You are heading two problems:
variable scope
value of variable $Foo is static and never change - value is always: Bar0 even when you change $aCount because the value is just a string
working example:
<?php
$aCount= 0;
$Foo = function(){ global $aCount; return "Bar".$aCount; };
${$Foo()} = array("Data1"=>NULL, "Data2"=>NULL);
function getBarData1() {
global $Foo, ${$Foo()};
return ${$Foo()}['Data1'];
}
function getBarData2() {
global $Foo, ${$Foo()};
return ${$Foo()}['Data2'];
}
function setBarData($newBarData1, $newBarData2) {
global $aCount, $Foo, ${$Foo()};
${$Foo()}['Data1'] = $newBarData1;
${$Foo()}['Data2'] = $newBarData2;
$aCount++;
}
setBarData('First', 'Line');
setBarData('Second', 'Dot');
setBarData('Third', 'Dash');
$aCountTotal = $aCount;
for($i = 0; $i < $aCountTotal; $i++) {
$aCount = $i;
echo getBarData1() ."\n";
echo getBarData2() ."\n";
}
in this case you should use array instead, variable-variable is really usefull in rare cases
array example:
<?php
$arr = array();
function getBarData1($index) {
global $arr;
return $arr[$index]['Data1'];
}
function getBarData2($index) {
global $arr;
return $arr[$index]['Data2'];
}
function setBarData($newBarData1, $newBarData2) {
global $arr;
$arr[] = ['Data1' => $newBarData1, 'Data2' => $newBarData2];
}
setBarData('First', 'Line');
setBarData('Second', 'Dot');
setBarData('Third', 'Dash');
for($i = 0; $i < count($arr); $i++) {
echo getBarData1($i) ."\n";
echo getBarData2($i) ."\n";
}
better than using global variable in functions is passing data through parameters like:
<?php
$arr = array();
function getData1($array, $index) {
return $array[$index]['Data1'];
}
function getData2($array, $index) {
return $array[$index]['Data2'];
}
// reference to $array because we want to change the value
function setData(&$array, $newBarData1, $newBarData2) {
$array[] = ['Data1' => $newBarData1, 'Data2' => $newBarData2];
}
setData($arr, 'First', 'Line');
setData($arr, 'Second', 'Dot');
setData($arr, 'Third', 'Dash');
for($i = 0; $i < count($arr); $i++) {
echo getData1($arr, $i) ."\n";
echo getData2($arr, $i) ."\n";
}

PHP, How can I sum-up the numeric values after calling a function from within a class?

The program deals 5 cards to each player displaying images of the cards along with the cards number value, after user selects number of players.
Everything works as described above, but I don't know how to total the values after calling the function. Can anyone give me an idea?
<?php
class classHand
{
var $totals;
var $cards;
function drawCard($c, $theDeck)
{
if (is_numeric($c)) {
$c = floor($c);
for ($i = 0; $i < $c; $i++) {
$this->cards[] = $theDeck->dealCard();
}
}
}
function showHand()
{
print("<table border=0>\n");
print("<tr><td> </td>\n");
for ($i = 0; $i < count($this->cards); $i++) {
print("<td>" . $this->cards[$i]->getImage() . "</td><td> </td>\n");
}
print("</tr></table>\n");
}
function showValue()
{
for ($i = 0; $i < count($this->cards); $i++) {
print(" " . $this->cards[$i]->getValue() . " ");
}
} // end of showValue
} // end of classHand
class classPlayer
{
var $name;
var $hand;
function classPlayer($n = "player")
{
$this->name = $n;
$this->hand = new classHand();
}
}
Then this is the page that implements the classes called cards.php
<?php
include("classCard.php");
$dealersDeck = new classDeck();
$dealersDeck->shuffleDeck();
$player[] = new classPlayer("You");
$selected_players = $_POST['players'];
for ($i = 0; $i < 5; $i++) {
for ($j = 0; $j < count($player); $j++) {
$player[$j]->hand->drawCard(1, $dealersDeck);
}
}
for ($i = 0; $i < count($player); $i++) {
print("Player: " . $player[$i]->name . "<br />");
$player[$i]->hand->showHand();
$player[$i]->hand->showValue();
print("<P> </p>");
}
Your $totals property wasn't used, so I renamed it to $totalValue. In this variable, you keep track of the cards in the hand.
class Hand
{
protected $totalValue;
protected $cards;
public function __construct()
{
$this->reset();
}
/**
* $deck is the only required parameter
*/
public function drawCard($deck, $count = 1, $reset = false)
{
// reset the counter
$this->reset();
if (!is_numeric($count)) return;
for ($i = 0; $i < $ccount; $i++) {
$this->addCard($deck->dealCard());
}
}
public function addCard(Card $card)
{
$this->totalValue += $card->getValue();
$this->cards[] = $card;
}
function getTotalValue()
{
return $this->totalValue;
}
public function reset()
{
$this->totalValue = 0;
$this->cards = array();
}
}
Now you can get the value of the Hand:
$deck = new Deck();
$players[] = new Player("You");
// start with 5 cards
foreach ($players as $player) {
$player->getHand()->drawCard($deck, 5);
}
// each player draws a card
foreach ($players as $player) {
$player->getHand()->drawCard($deck);
}
// get totals
foreach ($players as $player) {
print("Player: " . $player->getName() . "<br />");
$player->getHand()->getTotalValue();
print("<P> </p>");
}
// start again with new 5 cards
foreach ($players as $player) {
$player->getHand()->drawCard($deck, 5, true); // reseting with the 3rd param
}
You don't need to prefix your class names with class, and public properties are considered "not done". Normal practice is to set all properties to protected at minimum, and add accessor functions (get..() and set...())
And in this particular example, I would even consider merging the Player and Hand classes, because they kind of resemble the same thing. Unless the Player object is a generic user object you will reuse in many places of course.
function drawCard($c,$theDeck){
if(is_numeric($c)){
$c=floor($c);
for($i=0;$i<$c;$i++){
$this->cards[] = $theDeck->dealCard();
$this->total += $theDeck->dealCard()->getValue();
}
}
}
function getTotal(){
return $this->total;
}

attempting to initialize php variables in constructor, getting error

I'm trying to initialize a class attribute within a php constructor method, but am getting the error:
Notice: Undefined variable: _board in C:\wamp\scaleUp\back\objects.php on line 9
code:
<?php
class Board {
public function __construct(){
for ($x = 9; $x >= 0; $x--) {
for ($y = 0; $y<10; $y++){
$row = array();
$row[$y] = $y;
}
$this->$_board = array();
$this->$_board[$x] = $row;
}
echo "here";
echo $this->$board[$x];
}
}
$board = new Board();
?>
The syntax to access an object field is $obj->field, not $obj->$field (unless you want to access the field name that is stored in $field).
Here, I have debugged the code for you.
<?php
class Board {
public $_board;
public function __construct(){
for ($x = 9; $x >= 0; $x--) {
for ($y = 0; $y<10; $y++){
$row = array();
$row[$y] = $y;
}
$this->_board = array();
$this->_board[$x] = $row;
}
echo "here";
echo $this->_board[$x+1];/*OR*/print_r($this->_board[$x+1]);
//$x had to be incremented here.
}
}
$board = new Board();
?>
As others mentioned, you have to follow the syntax: $obj->property, not $obj->$property.
remove the $ from _board -
$this->_board = array();
It should be
$this->board
You don't need the second $ sign.
Also, in your constructor, in the inner loop, you are re-initializing $row as an array in every iteration. Is that intended?
You have to define your variable as a member variable
suck as
class object {
$_board ;
...
...
...
}
and when you want to use it you have to use the following syntax
$this->_board = .....;
I hope this helps you

PHP Foreach on array of objects

Why, if I have array of objects like this:
class testClass {
private $_x = 10;
public function setX($x) {
$this->_x = $x;
}
public function writeX() {
echo $this->_x . '<br />';
}
}
$t = array();
for ($i = 0; $i < 10; $i++) {
$t[] = new testClass();
}
print_r($t);
I can iterate by foreach like this:
foreach ($t as $tt) {
$tt->y = 7;
$tt->setX($counter);
$counter+=100;
}
print_r($t);
Or this:
foreach ($t as &$tt) {
$tt->y = 7;
$tt->setX($counter);
$counter+=100;
}
print_r($t);
And result will be equal? But if i have scalar values in array, they can only be modified by ($arr as &$v), $v only by reference ?
It depends on whether you're using PHP5 or an earlier version.
In PHP5, same thing because it is an array of objects. (Not the same thing for other types.)
In PHP4, not the same thing. (But then again, the second one will complain about a syntax anyway.)

Categories