php global variable and instance variable utilization - php

I'm having hard time accomplishing one simple task. I have a method that would generate random number and depending on the outcome assign specific outcome to an array variable. What i want to do is get that array variable through instance method which would be called from the other class.
<?php
class MyClass
{
public $results = array(array());
public function simulated_games()
{
$game_series1=array(23,34,56);
$game_series2=array(31,42,67);
$iter_wins=array(array());
for($i=0; $i<10;$i++)
{
$random = rand(0,100);
for($b=0; $b<1;$b++)
{
if($random <= $game_series1[0])
{
$iter_wins[$i][$b]=3;
}
else if($random <= $game_series2[0]+$game_series2[1])
{
$iter_wins[$i][$b]=1;
}
}
}
$results=$iter_wins;
}
>here i create method just to return variable
public function get_simulated_games()
{
return $this->results;
}
}
<?php
$a= new MyClass();
$a->simulated_games();
$array = array();
>here is the issue, it return just 1, but supposed to return range numbers
$array=$a->get_simulated_games();
for($f=0; $f<sizeof($array);$f++)
{
for($g=0; $g<5;$g++)
{
echo $array[$f][$g];
}
echo '<br>';
}
?>

You have the error in results.
You modify interal function variable which is not set instead of class variable
change
$results=$iter_wins;
to
$this->results=$iter_wins;

Related

Laravel recursion - calling itself in a class

My current code:
public function countThreads() {
$count = $this->threads->count();
if ($this->hasSubforum()) {
foreach ($this->subforums as $subforum) {
$count += $this->countThreads($subforum);
}
}
return $count;
}
I am currently accessing the "thread" as $this inside my model. I need to pass in the $subforum to itself but how can I do that in a class?
In my controller, I'm simply doing:
$forum = Forum::where('id', $id)->first();
$forum->countThreads();
How can I do recursion with this? thanks!
You don't need to pass any arguments*, you can call the countThreads method on the subforum $subforum->countThreads()
public function countThreads()
{
$count = $this->threads->count();
if ($this->hasSubforum()) {
foreach ($this->subforums as $subforum) {
$count += $subforum->countThreads();
}
}
return $count;
}
If you really want to pass it in as an argument, the correct way would be to write it as a service outside of the model

How to get output of count variable?

<?php
$count=0;
class My extends Thread
{
private $myid;
// ini_set('max_execution_time', 0);
//echo date("Y-m-d H:i:s")."<br/>";
public function __construct($id)
{
$this->myid = $id;
}
public function run()
{
for($t=0;$j+$t<=100;$t+=10){ //future buy
for($k=0;$j+$t+$k<=100;$k+=10){//future sell
for($l=1;$l<=14;$l++){ // strike
for($m=0;$j+$k+$m<=300;$m+=10){ //put buy
for($n=1;$n<=14;$n++){ // strike
for($o=0;$o<=300;$o+=10){ // call buy
for($p=1;$p<=14;$p++){ //strike
if($p==$l)
continue;
for($q=0;$q<=300;$q+=10){ // put sell
for($r=1;$r<=14;$r++){ // strike
if($r==$n)
continue;
for($s=0;$s<=300;$s+=10){ // call buy
$count ++;
}
}
}
}
}
}
}
}
}
}
}
}
echo date("Y-m-d H:i:s")."<br/>";
$mycalls = [];
for($i=0;$i<=100;$i+=10)
{
$mycalls[$i]= new My($i);
$mycalls[$i]->start();
$mycalls[$i]->join();
}
echo date("Y-m-d H:i:s")."<br/>";
echo "<br>";
echo $count;
?>
Call run method of My class. and it should be either return $count or echo $count.
Not sure I completely understand what you mean by "how to get output of count variable", but I see a number of problems there might occur.
1) $count is a global variable and not a class or a method variable, which menas that simply adding 1 to count in th run method will not do any changes in $count outside the class definition.
2) I don't see any place where run method that updates $count (despite the fact that it is outside the class) variable is called.
3) Even if run method is somewhere called you have to add a line global $count at the beginning of run method.
4) I would suggest you store the $count internally in the class and return it with a function, which would mean that the class looks something like this:
Class My extends Thread{
protected $count = 0;
public function run(){
//...
$this -> count++;
//...
}
public function getCount(){
return $this -> count();
}
}
And then get the count value from the class instance:
$myInstance = new My();
$myInstance -> run();
$someCount = $myInstance -> getCount();
Due to the fact that you are creating 101 instances of my, the code would look something like this:
$mycalls = [];
$count = 0;
for($i=0;$i<=100;$i+=10)
{
$mycalls[$i]= new My($i);
$mycalls[$i]->start();
$mycalls[$i]->join();
$count += $mycalls[$i] -> getCount();
}
echo $count;

Trying to stack values with PHP

Im currently trying to make a little dice game in php. Right now Im trying to make a "currentscore" where all the points from a rand(1,6) are stacked into a single variable.
Here is the class Im doing this in:
<?php
class CDice {
public $roll;
public $currentscore;
public function Roll()
{
$this->roll = rand(1,6);
return $this->roll;
}
public function currentScore()
{
$this->currentscore += $this->roll;
return $this->currentscore;
}
}
I don't under stand why $this->currentscore += $this->roll; doesn't work.
You do realise that at the end of execution of this class no values are kept right? If you wish to transfer over this data to the next page render, you should use PHP sessions.
<?php
class CDice {
public $roll;
public $currentscore = 0;
public function Roll(){
$this->roll = rand(1,6);
$this->currentscore += $this->roll;
return $this->roll;
}
public function currentScore(){
return $this->currentscore;
}
public function __construct(){
if(session_status() == PHP_SESSION_ACTIVE){
$this->currentscore = isset($_SESSION['dice.score']) ? $_SESSION['dice.score'] ? 0;
# In PHP 7.0
# $this->currentscore = $_SESSION['dice.score'] ?? 0;
} else {
echo 'session has not been initiated';
}
}
}
session_start();
$tmp = new CDice();
echo $tmp->Roll();
echo $tmp->Roll();
echo $tmp->currentScore();
?>
Also not assigning an "initalial" value to a variable before trying to add things to it with +=, -=, etc causes PHP to throw a warning.

Preserving variable values within a PHP function

I have a function which I call multiple times within a script. The value returned from the function will always be the same. I would rather not execute all the script within the function each time since the returned value is always the same. I am not using OOP so can't assign it to a object property and do the script in the constructor.
Below is my attempt. It doesn't work since $status is not set until it later is defined as a static variable. How can I accomplish my goal?
function checkStatus()
{
if(!isset($status))
{
//Do some script to determine $cond
if($cond) {static $status=0;}
else {static $status=1;}
}
return $status;
}
This should do what you need:
function checkStatus()
{
static $status;
if(!isset($status))
{
if (TRUE) // Whatever your truth condition will be
{
$status = 1;
}
else
{
$status = 0;
}
}
return $status;
}
You could pass the variable by reference: http://www.php.net/manual/en/language.references.pass.php
function checkStatus(&$status)
{
//Do some script to determine $cond
if($status == 0) {
$status=1;
}
else {
$status=0;
}
}
$status = 0;
checkStatus($status);
echo $status; //this should display 1;

php session variable

my session variable seems to keep dropping its array values. What could I be doing wrong? Is it my object?
session_start() is initiated at the beginning,
if(isset($_SESSION['locations'])) {
unserialize($_SESSION['locations'])->listItems($_POST['companyLocation']);
echo "session exists";
}
else{
$_SESSION['locations'] = serialize(new Location());
unserialize($_SESSION['locations'])->listItems($_POST['companyLocation']);
echo "session does not exist";
}
class Location{
function listItems($location){
$array;
$array[] = $location;
//print_r($array);
// Re-index:
$array = array_values($array);
print_r($array);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
echo "{$array[$i]}\n";
}
}
}
Do you have the following line at the beginning of your php script?
<?php
session_start();
...
Looking at your Location class, the listItems function looks horribly broken, what is is that you're trying to do?
A quick refactor of your Location class based on your comment:
class Location {
private $locations;
public static function instance($args = null) {
return empty($_SESSION['locations']) ?
new Location($args) : unserialize($_SESSION['locations']);
}
public function __construct($locations = null) {
$this->locations = empty($locations) ? array() : $locations;
}
public function addLocation($location) {
$this->locations[] = $location;
}
public function listItems() {
print_r($this->locations);
}
public function saveInstance() {
$_SESSION['locations'] = serialize($this);
}
}
Usage would be:
<?php
session_start();
$location = Location::instance();
if(!empty($_REQUEST['companyLocation']));
$location->addLocation($_REQUEST['companyLocation']);
$location->listItems();
...
$location->saveInstance();
?>
The first things that come to mind:
Are you remembering to use session_start() at the top of every page, before headers are sent? if not, then no session information is stored between pages.
$_SESSION['locations'] is being set to an object. You never serialized the object, which can cause issues trying to store it into a session. See http://www.php.net/manual/en/language.oop5.serialization.php for more information on object serialization, and storing them in the session object.

Categories