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);
}
}
?>
Related
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.
Hy,
i started learning PHP and i created a simple MVC Style Codebase.
The Script just generates a random number and displays this numer. I also write a function to display the number shown before but it does not work. The value is empty. Can you help me out, i have no clue whats wrong and there is no php error thrown.
view.php
<?php
class View
{
private $model;
private $view;
public function __construct()
{
$this->model = new Model();
}
public function output()
{
echo 'Current Entry: ';
echo $this->model->getData();
echo '<br />';
echo 'Update';
echo '<br />';
echo 'Last';
}
public function getModel()
{
return $this->model;
}
}
controller.php
<?php
class Controller
{
private $model;
private $view;
public function __construct($view)
{
$this->view = $view;
$this->model = $this->view->getModel();
}
public function get($request)
{
if (isset($request['action']))
{
if ($request['action'] === 'update')
{
for ($i = 0; $i<6; $i++)
{
$a .= mt_rand(0,9);
}
$this->model->setData($a);
}
elseif ($request['action'] === 'preview')
{
$this->model->setLast();
}
else
{
$this->model->setData('Wrong Action');
}
}
else
{
$this->model->setData('Bad Request');
}
}
}
model.php
<?php
class Model
{
private $data;
private $last;
public function __construct()
{
$this->data = 'Default';
}
public function setData($set)
{
if ( ! (($set == 'Wrong Action') && ($set == 'Bad Request')))
{
$this->last = $this->data;
}
$this->data = $set;
}
public function getData()
{
return $this->data;
}
public function setLast()
{
$this->data = $this->last;
}
public function getLast()
{
return $this->last;
}
}
index.php
<?php
require_once 'controller.php';
require_once 'view.php';
require_once 'model.php';
$view = new View();
$controller = new Controller($view);
if (isset($_GET) && !empty($_GET)) {
$controller->get($_GET);
}
$view->output();
Are there any other, bad mistakes in the Script?
Any input very welcome! :)
The problem with your code is that PHP does not preserve variable values between requests, therefore, when you set your $model->last value here:
$this->last = $this->data;
It gets reset on your next request.
You may want to store $last value in a session or a cookie instead. Something like:
$_SESSION['last'] = $this->data;
And then when you are instantiating your model you could initialize it with a value stored in a session if available:
index.php - add session_start() at the beginning
model.php:
public function __construct()
{
$this->data = isset($_SESSION['last']) ? $_SESSION['last'] : 'Default';
}
public function setData($set)
{
$this->data = $set;
if ( ! (($set == 'Wrong Action') && ($set == 'Bad Request')))
{
$_SESSION['last'] = $this->data;
}
}
controller.php
elseif ($request['action'] === 'preview')
{
//Remove this
//$this->model->setLast();
}
Working on a project of translating website and I had chose this solution
.
I'm trying to accomplish something like :
$VAR1 = $translate->__('Word_To_Translate');
This, not works for me since, the result is directly shown in stdout of the webpage. Even so when trying to call $VAR1 no result is returned.
This is not easily possible with the class you've mentioned.
If you wish to edit the class so it'll return the value instead of echoing it, you can edit class.translation.php, replace the two occurances of echo $str; with return $str;, and replace echo $this->lang[$this->language][$str]; with return $this->lang[$this->language][$str] (simply changing echo to return on both instances).
//$VAR1 delegating
$VAR1 = $translate->__('Word_To_Translate');
//class.translation.php
`class Translator {
private $language = 'en';
private $lang = array();
public function __construct($language){
$this->language = $language;
}
private function findString($str) {
if (array_key_exists($str, $this->lang[$this->language])) {
return $this->lang[$this->language][$str];
return;
}
return $str;
}
private function splitStrings($str) {
return explode('=',trim($str));
}
public function __($str) {
if (!array_key_exists($this->language, $this->lang)) {
if (file_exists($this->language.'.txt')) {
$strings = array_map(array($this,'splitStrings'),file($this->language.'.txt'));
foreach ($strings as $k => $v) {
$this->lang[$this->language][$v[0]] = $v[1];
}
return $this->findString($str);
}
else {
return $str;
}
}
else {
return $this->findString($str);
}
}
}`
Switched the echo for a return
Thank you very much uri2x && Rizier123.
For the moment looks that it is working solution.
Best wishes !
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');
}
}
}
}
?>
I'm using codeigniter as a framework.
Firstly, I use:
public function edit_ads_wait($id)
{
$where["user"]=$this->session->userdata("userid");
$where["id"]=$id;
$where["state"]=2;
$info=$this->base->get_where_row("advertisement",$where);
if($info) // if $info isset
{
$where_cat["deleted"]=0;
$data["info"]=$info;
$data["category"]=$this->base->get_where("category",$where_cat,$order);
$data["region"]=$this->base->get("region");
$this->userskin->loadview("user/ads/edit_ads",$data);
}else // if $info is not set
{
$this->clear_session();
}
}
when i execute edit_ads_wait function -where the $info isset- it also run clear_session() function and my session is cleared
the clear_session is
function clear_session()
{
foreach ($this->session->all_userdata() as $key=>$val)
{
if(strlen($key)>=20)
{
$this->session->unset_userdata($key);
}
//print_r($key);
}
}
please help me...
i guess you are using the function inside of the "view" not the "controller", if so
a quick fix : try to add exit(); at the end of your if condition before the else .
or if your function inside your controller class make sure the class looks like that
ex : if the controller file name is example.php :
<?php
class Example extends CI_Controller {
//your constructor
function exmple() {
parent::__construct();
// you can load libraries and helpers here
}
// your other functions
}
?>
Can you please try this:
if $info is an array then:
if(isset($info) && !empty($info))
if $info is a single value then:
if(isset($info) && $info != '')