changing variable value outside a function inside a class - php

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

Related

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

Using For loop to call a function

I need some help with this function to finish my project.
3 variables:
$cityName1 = "New York";
$cityName2 = "Madrid";
$cityName3 = "Paris";
The function:
function cityNameFunction($cityName) {
$city_name = $cityName;
return $city_name;
}
Calling the function:
$cityName = array();
for($x = 1; $x <= 3; $x++) {
$cityName[$x] = ${'cityName'.$x};
}
$cityName1 = cityNameFunction($cityName1);
$cityName2 = cityNameFunction($cityName2);
$cityName3 = cityNameFunction($cityName3);
What do I have to do if I have 2000 cities?
Thanks for any help
Strange example, but you may write something like this
$cityName = array();
for ($x = 1; $x <= 3; $x++) {
$cityName[$x] = ${'cityName'.$x};
${'cityName'.$x} = cityNameFunction(${'cityName'.$x});
}
An example of Itterating over a PHP Function at work:
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++)
{
$val = $new[$i];
if(!function_exists('myfunction'))
{
function myfunction($value) {
//Do something
}
}
echo $val;
}

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

PHP - Modify array value by reference inside object

How can I pass a value of an array by reference to modify its value inside an object? I've tried it with the & operator at public function f(&$z) {.
<?php
class C {
private $a;
public function f($z) {
foreach ($z as $i => $v) {
$v = 8888;
}
}
}
$p = 4;
$obj = new C();
$obj->f(array('key'=>$p));
echo $p;
?>
I would like to set the 8888 value to the $p variable.
The fiddle: http://codepad.org/RvKU4hY1
You have to use references when you 1) create the array, 2) iterate over it:
<?php
class C {
private $a;
public function f($z) {
foreach ($z as $i => &$v) {
$v = 8888;
}
}
}
$p = 4;
$obj = new C();
$obj->f(array('key'=>&$p));
echo $p;
?>
Only slightly different to georg, you can do it this way;
<?php
class C {
private $a;
public function f($z) {
foreach ($z as $i => $v) {
$z[$i] = 8888;
}
}
}
$p = 4;
$obj = new C();
$result = array('key'=> &$p);
$obj->f($result);
echo $p;
?>
Here the code with explanation:
<?php
class C {
private $a;
public function f(&$z) { // we receive a pointer
foreach ($z as $i => $v) {
// here you overwrite $v, even if it a pointer in foreach
// It has mean when you want to do unset($v); here
// $v = 8888;
$z[$i] = 8888;
}
}
}
$p = 4;
$obj = new C();
$param = array('key'=>$p);
$obj->f($param);
echo $p;

Initialising an array of objects

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

Categories