issue with incrementing a variable in cakephp (basics) - php

Basically this is just a guessing game so that I can learn the ins and outs of cake.
I'm trying to keep track of the users number of guesses on every page reload (using a variable name $user_loop). When I try to increment it, it stays static or only increments by one and stops. I've placed the increment snippet in my view also to only receive the same results. Any help would be great.
<?php
class GuessController extends AppController {
public $uses = array();
function beforeFilter() {
if (!$this->Session->check('Random.Num')) {
$this->Session->write('Random.Num', rand(1, 9));
}
}
function create() {
if ($this->request->is('post', 'put')) {
$rn = $this->Session->read('Random.Num');
$user_guess = $this->request->data['Guess']['guess'];
$this->set('user_guess', $user_guess);
$user_loop++ // <- Also getting undefined variable here
echo $user_loop; //for testing
if ($rn == $user_guess) {
echo 'Cashe Cleared';
$this->Session->delete('Random');
}
}
}
}
?>

Try this :
<?php
class GuessController extends AppController {
public $uses = array();
function beforeFilter() {
if (!$this->Session->check('Random.Num')) {
$this->Session->write('Random.Num', rand(1, 9));
}
if(!$this->Session->check('user_loop')) {
$this->Session->write('user_loop',0);
}
}
function create() {
if ($this->request->is('post', 'put')) {
$rn = $this->Session->read('Random.Num');
$user_guess = $this->request->data['Guess']['guess'];
$this->set('user_guess', $user_guess);
$user_loop = $this->Session->read('user_loop')+1;
echo $user_loop; //for testing
$this->Session->write('user_loop',$user_loop);
if ($rn == $user_guess) {
echo 'Cash Cleared';
$this->Session->delete('Random');
}
}
}
}
?>

Related

How define variable in laravel component

i use laravel 8 components, that according to doc can pass data and use it. but i need some modification passed data as variable that can be used in component
my code got Undefined variable: covers error
<x-item_h :item="$item"/>
item-h.blade.php
<div class="item-h">
{{$item}}
{{$covers}}
</div>
item-h.php
class Item_h extends Component
{
public $item;
public $covers;
public function __construct($item )
{
$this->item = $item;
if ($item->getCover->count() > 0) {
$covers = $item->getCover;
} else {
$covers = $item->artists->getCover;
}
}
public function render()
{
return view('components.item_h');
}
}
so how define variable in component that can be use in it ?
Thanks
First, you need to add covers as when u are calling the component like this.
<x-item_h :item="$item" covers/>
Now update the constructor and add give covers a default value of your choice, so that even u forget to give value to it, it will not crash your view
class Item_h extends Component
{
public $item;
public $covers;
public function __construct($item ,$covers={{REPLACE WITH DEFAULT VALUE}})
{
$this->item = $item;
$this->covers = $covers;
if ($item->getCover->count() > 0) {
$covers = $item->getCover;
} else {
$covers = $item->artists->getCover;
}
}
public function render()
{
return view('components.item_h');
}
}
I am sure this will fix your issue

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.

Pass variables from class instance to its extended method

I'm trying to pass a variable to a method in an extended class, but it's not working.
Here's the sample code:
class set2 extends set1
{
function Body($variable) {
}
}
$start2 = new set2();
$start2->Body('some text');
The last line is the part I'm trying to get to work. I'm not sure if I should have a constructor instead to do it or how it's best to get it to work.
I figured it out. I just added a public variable instead and passed its value like this:
class set2 extends set1
{
public $variable = NULL;
function Body() {
echo $this->variable;
}
}
$start2 = new set2();
$start2->variable = 'Some Text';
Three different ways of doing what I think you're trying to do:
class set1
{
protected $headVariable;
function Head() {
echo $this->headVariable;
}
function Body($variable) {
echo $variable;
}
function Foot() {
echo static::$footVariable;
}
}
class set2 extends set1
{
protected static $footVariable;
function Head($variable) {
$this->headVariable = $variable;
parent::Head();
}
function Body($variable) {
parent::Body($variable);
}
function Foot($variable) {
self::$footVariable = $variable;
parent::Foot();
}
}
$start2 = new set2();
$start2->Head('some text');
$start2->Body('some more text');
$start2->Foot('yet more text');

Creating multilanguage homepage translating

Okay, so i got class file, in which i got function -
var $text;
public function languages()
{
if (isset($_GET['lang']) && $_GET['lang'] != '')
{
$_SESSION['lang'] = $_GET['lang'];
}
switch($_SESSION['lang'])
{
case 'en_EN': require_once('language/lang.eng.php');break;
case 'lv_LV': require_once('language/lang.lv.php');break;
case 'ru_RU': require_once('language/lang.ru.php');break;
default: require_once('language/lang.eng.php');
}
$this->text = $text;
}
public function translate($txt)
{
if(isset($this->text[$txt]))
{
return $this->text[$txt];
}
}
If i am translating via index.php like this - > echo $index->translate('search'); it translates ok, but if i am translating something in class file for example -
if ($country_rows > 0)
{
$_SESSION['country'] = $_GET['country'];
}
else
{
$_SESSION['country'] = $this->translate('all_countries');
}
}
if ($_SESSION['country'] == '')
{
$_SESSION['country'] = $this->translate('all_countries');
}
it doesn't show up.
In index.php header i got included -
require_once('class.index.php');
$index = new index;
$index->get_country();
$index->languages();
What could be the problem, and how can i fix it, so i can translate everything inside class file too? will appreciate your help!
1st guess:
no session started?
session_start();
2nd guess:
assuming that you use $this->translate() in another class, you should initiate the object first, in the following example I pass translate class to var $index;
<?
include_once('class.index.php');
class myClass {
var $index;
public function __construct() {
$index = new index();
$index->get_country();
$index->languages();
$this->index = $index;
}
public function yourFunction() {
echo $this->index->translate('all_countries');
print_r($this->index);
}
}
?>

PHP class: Unable to access array in another function

I tried a lot of search but unable to figure out why array $wordlinks in function DoWordLink is not carrying values from function __construct. PHP class code as below:
<?php
class autolinkkeyword
{
public $wordlinks = array();
public function __construct(){
$query = mysql_query("SELECT keyword FROM library");
while ($row = mysql_fetch_array($query))
{
$this->wordlinks [$row["keyword"]] = $row["keyword"];
}
}
public function linkkeywords ($posts)
{
function DoWordLink($match)
{
$rpl=$match[1];
if(isset($wordlinks[$rpl]))
{
$kword = $this->wordlinks[$rpl];
$rpl="<a class=\"keyword_link\" href=\"#\" onclick=\"popup('popUpDiv');
ajax_loadContent('kword', 'library.php?keyword=$kword')\">$kword</a>";
unset($this->wordlinks[$match[1]]);
}
return $rpl;
}
$wl=array_keys($this->wordlinks);
$pm="/((?<=\s|^)(?:" . implode('|',$wl) .")(?=\.|\!|\?|\,|\'|\s|$))/im";
foreach($posts as $key => $mainbody)
{
$mainbody=preg_replace_callback($pm, 'DoWordLink', $mainbody) ;
echo $mainbody;
}
}
}
?>
You can make it an actual method of that class and call it using this method:
http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback
like:
preg_replace_callback($pm, array($this, 'DoWordLink'), $mainbody);
Change DoWordLink function so it is part of the class like:
class autolinkkeyword
{
function DoWordLink($match)
{
$rpl=$match[1];
if(isset($this->wordlinks[$rpl]))
{
$kword = $this->wordlinks[$rpl];
$rpl="<a class=\"keyword_link\" href=\"#\" onclick=\"popup('popUpDiv');
ajax_loadContent('kword', 'library.php?keyword=$kword')\">$kword</a>";
unset($this->wordlinks[$match[1]]);
}
return $rpl;
}
}
aren't you missing a "this->" construct here? if(isset($this->wordlinks[$rpl]))
Use the $this everywhere you refer to $wordlinks.
$this->wordlinks
You need to access the property in your linkkeywords-method with the object-accessor, too!
public function linkkeywords ($posts)
{
// Here use $this->wordlinks not $wordlinks
}

Categories