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.
Related
<?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;
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.
I have this class which populates and prints an array
<?php
class testArray
{
private $myArr;
public function __construct() {
$myArr = array();
}
public static function PopulateArr() {
$testA = new testArray();
$testA->populateProtectedArr();
return $testA;
}
protected function populateProtectedArr()
{
$this->myArr[0] = 'red';
$this->myArr[1] = 'green';
$this->myArr[2] = 'yellow';
print_r ($this->myArr);
}
public function printArr() {
echo "<br> 2nd Array";
print_r ($this->myArr);
}
}
?>
I instantiate this class from another file and try to print the array in different function.
<?php
require_once "testClass.php";
$u = new testArray();
$u->PopulateArr();
$u->printArr();
?>
I am not able to print the array in the printArr() function. I want to get reference to the array that I had set the values in .
You just missed one thing, you have to assign result of $u->PopulateArr(); to $u again, otherwise you will not get the object you created from that method call, so:
$u = new testArray();
$u = $u->PopulateArr(); // this will work
$u->printArr();
This also can be done like this:
$u = testArray::PopulateArr();
$u->printArr();
It seems that your $u object never populates the private array.
Instead you create a new object $testA and populate its array.
This might help you understanding the way
class testArray
{
private $myArr;
public function __construct() {
$this->myArr = array();
}
public static function PopulateArr() {
$testA = new testArray();
$testA->populateProtectedArr();
return $testA;
}
protected function populateProtectedArr()
{
$this->myArr[0] = 'red';
$this->myArr[1] = 'green';
$this->myArr[2] = 'yellow';
return $this->myArr;
}
public function printArr() {
echo "<br> 2nd Array";
return $this->PopulateArr();
}
}
another.php
require_once "testClass.php";
$u = new testArray();
print_r($u->PopulateArr());
print_r($u->printArr());
Here we are accessing the values of protected function PopulateArr instead of printing within function I just replaced it with return and print it over another file and within printArr function just call the PopulateArr function and that's it
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;
Is PHP exists a function that detect the change of variable?
That is something like this:
//called when $a is changed.
function variableChanged($value) {
echo "value changed to " . $value;
}
$a = 1;
//attach the variable to the method.
$a.attachTo("variableChanged");
$a = 2;
$a = 3;
//expected output:
//value changed to 2
//value changed to 3
I know that it is easy to achieve if I use the "setter" method. But since I am working on some existing codes, I am not able to modify them. Can somebody tell me how to achieve my purpose? Thanks.
know that it is easy to achieve if I use the "setter" method. But since I am working on some existing codes, I am not able to modify them.
I assume that you can change some code, but not the object / class you are working with. If you cannot change any code at all this question would be useless.
What you can do is make your own class, extending the class you are working with, and adding your setter there. For all purposes you can not-override the parent setting, except for a magic setter on whatever you need to track. Track changes and then call the parent functions, so no changes in any other internal workings will be in effect.
This could only be achieved by wrapping your variable within a class, and implementing a onchange yourself.
ie.
class MyVarContainer {
var $internalVar = array();
function __get($name) {
return !empty($this->internalVar[$name]) $this->internalVar[$name] ? FALSE;
}
function __set($name, $value) {
$oldval = $this->$name;
$this->internalVar[$name] = $value;
if($oldval !== FALSE) {
onUpdated($name, $oldval, $value);
} else {
onCreated($name, $value);
}
}
function onCreated($name, $value) {
}
function onUpdated($name, $oldvalue, $newvalue) {
}
}
You could revised your code as simple like this just to produce that expected output you want.
function variableChanged($value) {
return "value changed to " . $value;
}
$a = 1;
echo $a = variableChanged(2);
echo '<br/>';
echo $a = variablechanged(3);
=================
//output
value changed to 2
value changed to 3
or using a class like this....
class VariableHandler{
private $Variable;
function setVariable($initialValue = NULL){
$this->Variable = $initialValue;
return $initialValue;
}
function changeValue($newValue = NULL){
$this->Variable = $newValue;
return "value has change to ". $newValue;
}
}
$var = new VariableHandler;
echo $a = $var->setVariable(1);
echo '<br/>';
echo $var->changeValue(2);
echo '<br/>';
echo $var->changeValue(3);
=================
//output
value changed to 2
value changed to 3
Besides using a debugger:
The SplObserver interface is used alongside SplSubject to implement
the Observer Design Pattern.
http://www.php.net/manual/en/class.splobserver.php
Or the magic methods __get() and __set(): Encapsulating the variable into a class, you could implement a event handler yourself and register the change of a variable. Also you could attach callbacks like here:
<?php
header("content-type: text/plain");
class WatchVar {
private $data = array();
private $org = array();
private $callbacks = array();
public function __set($name, $value) {
if (!array_key_exists($name, $this->data)) {
$this->org[$name] = $value;
} else {
//variable gets changed again!
$this->triggerChangedEvent($name, $value);
}
$this->data[$name] = $value;
}
public function &__get($name) {
if (array_key_exists($name, $this->data)) {
if ($this->data[$name] != $this->org[$name]) {
//variable has changed, return original
//return $this->org[$name];
//or return new state:
return $this->data[$name];
} else {
//variable has not changed
return $this->data[$name];
}
}
}
public function addCallback($name, $lambdaFunc) {
$this->callbacks[$name] = $lambdaFunc;
}
protected function triggerChangedEvent($name, $value) {
//$this->data[$name] has been changed!
//callback call like:
call_user_func($this->callbacks[$name], $value);
}
}
$test = new WatchVar;
$test->addCallback('xxx', function($newValue) { echo "xxx has changed to {$newValue}\n"; });
$test->xxx = "aaa";
echo $test->xxx . "\n";
//output: aaa
$test->xxx = "bbb";
//output: xxx has changed to bbb
echo $test->xxx . "\n";
//output bbb
function messyFunction(&$var) {
$var = "test";
}
messyFunction($test->xxx);
//output: