how to make a global variable in yii - php

I am learning Yii and I wanted to ask a basic question.
I have a controller and there are two actions in that controller which are as follows
class MyappController extends Controller
{
public $count=0;
public function actionInitialCount()
{
$this->count=1;
$this->redirect('secondCount');
}
public function actionSecondCount()
{
echo $this->count;
}
}
Now what i want is that when the InitialCount action has modified the $count variable to 1. the secondCount to echo it as 1 and not 0. But it echos it as 0 only. So how can i achieve this task that if one action modifies a variable then i can get the modified values in the second action

I think, you are thinking about common variable between two life cycle of application. That is only possible with $_SESSION or other persistent variables . I hope, you understand this.

In side the controller function, you have to use the count variable as
$this->count
So, complete code will be :
class MyappController extends Controller {
public $count=0;
public function actionInitialCount()
{
$this->redirect('secondCount');
}
public function actionSecondCount()
{
echo $this->count;
}
}

Think that i have a class
class AController extends MyController{
//can be accessed here(even in the view) using $this->publicvariable
}
And I say that this is in components
class MyController extends CController{
//My public variable is declared here
}

Now i take different examples.
Example 1
It is simple PHP Program example.
class MyappController {
public $count = 0;
function InitialCount() {
$this->count = 1;
}
function SecondCount() {
print $this->count;
}
}
$ob = new MyappController();
$ob->InitialCount();
$ob->SecondCount();
Example 2
Above same program but in Yii.
class MyappController extends Controller
{
public $count=0;
function __construct() {
$this->count = 7 + 8 ;
}
public function actionIndex()
{
echo $this->count ;
}
public function actionInitialCount()
{
echo $this->count=1;
}
public function actionSecondCount()
{
echo $this->count ;
}
}
Example 3
We can change value by accessing it out side the class.
class MyTest
{
protected $a;
public function __construct($a)
{
$this->a = $a;
}
public function head()
{
echo $this->a;
}
public function footer()
{
echo $this->a;
}
}
$a = 7;
$obj = new MyTest($a);
echo $obj->head();
Actually when you modified your variable value, then you need to declare it, as i have declared in my 1st example, then you can get your changed value.
Secondly like in ecommerce applications, when we purchase different items then it will display modified values each, so it can be accessed through session varialbes, that store information on the server.
If you need your modified value in Yii and display it on the view, so you read about Yii Sessions then you can accomplish your requirement.
In my example of Yii, if you redirect it to the view then it will generate error because i have made Constructor.
Hope it will help you for your understanding.
Thanks.

Can you not just make count a session using Yii::app()->session['count']? What happens now is that the class is being loaded when you call actionInitialCount and again actionSecondCount so the $count will be set back to 0.

Related

Access variable across methods Laravel PHP

Hey all actually I too facing the problem but I couldn't understand any of the above methods. Please help me to understand those stuffs and help t fix my problem.
I have two methods method1 and method2, where I receive some value in method 1 which needs to used in method 2. I created a variable on class level but I couldn't access the variable below is the code snippet.
class testController extends controller
{
public $isChecked = false;
public $isSelectedValue = 0;
public function ValidateValue(Request $req)
{
$isChecked = $req->checked;
$isSelectedValue = $req->value;
}
public function UsethoseValues()
{
if ($isChecked) { // I can't use the variable here it throws run time error. I need help on this please help.
}
}
}
because you are in class and you declare a property not a simple variable
so when you try to access it from the method in your class you need to add $this
keyword that refer to your class
$this->isChecked
so your code will be like this after editing
class testController extends controller {
public $isChecked = false;
public $isSelectedValue = 0;
public function ValidateValue(Request $req) {
$this->isChecked = $req->checked;
$this->isSelectedValue = $req->value;
}
public function UsethoseValues() {
if($this->isChecked) { // I can't use the variable here it throws run time error. I need help on this please help.
}
}
}
feel free to check the docs for more info

Phalcon library class calling a function within another

Im using phalcon 2.0.0 and i am trying to call a function with in another function but from the same class like shown below, for some reason i get a blank page. And when i comment the calling of 2nd function from first, the page loads properly.
<?php
use Phalcon\Mvc\User\Component;
class Testhelper extends Component {
public function f1($data) {
$tmp = $this->f2($data);
return $tmp;
}
public function f2($data) {
return '5'; // just testing
}
}
And btw im accessing the f1 function by the volt function extender like this
$compiler->addFunction('customfunc', function($resolvedArgs, $exprArgs) {
return 'Testhelper ::f1('.$resolvedArgs.')';
});
if someone could help me, it would be deeply appreciated.
Thanks guys
You are trying to call TestHelper f1() statically in Volt, where your class does not expose that function as a static.
You can change your code like this:
<?php
use Phalcon\Mvc\User\Component;
class Testhelper extends Component
{
public static function f1($data)
{
$tmp = self::f2($data);
return $tmp;
}
public static function f2($data)
{
return '5'; // just testing
}
}
and your Volt function will work. However you have to bare in mind that because you are calling things statically you won't have immediate access to all the di container services that the Component offers like so:
$this->session
$this->db
You will need to modify your code to pick the di container using the getDefault()
Another option is to use the code as you have right now, but register the TestHelper in your di container like so:
$di->set(
'test_helper',
function () {
return new TestHelper();
}
);
and then your volt function will need to change to:
$compiler->addFunction(
'customfunc',
function ($resolvedArgs, $exprArgs) {
return '$this->test_helper->f1('.$resolvedArgs.')';
}
);

How do I use a variable within an extended class public variable

Have a class that I am using, I am overriding variables in the class to change them to what values I need, but I also not sure if or how to handle an issue. I need to add a key that is generated to each of this URLs before the class calls them. I cannot modify the class file itself.
use Theme/Ride
class ETicket extends Ride {
public $key='US20120303'; // Not in original class
public $accessURL1 = 'http://domain.com/keycheck.php?key='.$key;
public $accessURL2 = 'http://domain.com/keycheck.php?key='.$key;
}
I understand that you cannot use a variable in the setting of the public class variables. Just not sure what would be the way to actually do something like this in the proper format.
My OOP skills are weak. I admit it. So if someone has a suggestion on where I could read up on it and get a clue, it would be appreciated as well. I guess I need OOP for Dummies. =/
---- UPDATE ---
The initial RIDE class has 2 URLs set.
public $accessURL1 = "http://domain.com/index.php";
public $accessURL2 = "http://domain.com/index2.php";
I was to override them so the RIDE class will use my new domains.
I can add the following and it works...
class ETicket extends RIDE {
public $accessURL1 = 'http://mydomain.com/myindex.php';
public $accessURL2 = 'http://mydomain.com/myindex2.php';
}
However, I also want to pass a variable from elsewhere ($key) as a parameter to the URL when I override them so when i call RIDE it has a URL with the value of KEY at the end. (?key=keyvalue)
Your close, if you do not want to allow calling code to change the $key, you can do something like:
class ETicket extends Ride {
public function getKey()
{
return 'US20120303';
}
public function generateUrl()
{
return 'http://domain.com/keycheck.php?key=' . $this->getKey();
}
}
// Calling code example
$eTicket= new ETicket();
// $key is a member of ETicket class, so just call on generateUrl which will
// build and return the url
var_dump($eTicket->generateUrl());
You can also permit calling code to change the key if needed, by adding a public setter/getter:
class ETicket extends Ride {
protected $key;
public function setKey($key)
{
$this->key = $key;
}
public function getKey()
{
return $this->key;
}
public function generateUrl()
{
return 'http://domain.com/keycheck.php?key=' . $this->getKey();
}
}
// Calling code example
$eTicket= new ETicket();
$eTicket->setKey('US20120303');
var_dump($eTicket->generateUrl());
-- UPDATE --
There are a couple of options, you can either append the key to your url as part of the calling code, like this:
$eTicket= new ETicket();
$url = $ride->accessURL1 . '?key=US20120303';
Or, use a method (changed slightly to accept key directly) as I described earlier:
class ETicket extends Ride
{
public function generateUrl($key)
{
return $this->accessURL1 . '?key=' . $key;
}
}
$eTicket= new ETicket();
$url = $eTicket->generateUrl('US20120303');
I guess the point is, you cannot do what you originally asked without which is to concatenate a variable to a member variable initialization.

Create and use anonymous object in PHP

Say I have a simple class and I create it and call a function on it like this:
class tst
{
private $s = "";
public function __construct( $s )
{
$this->s = $s;
}
public function show()
{
return $this->s;
}
}
$t = new tst( "hello world" );
echo "showing " . $t->show() . "\n";
Is there any syntax or workaround that will allow me to instantiate an instance of tst and call the show() function without assigning the object to a variable? I want to do something like:
echo new tst( "again" )->show();
I don't want to declare my functions as static as I want to use them in both of the above examples.
You can't do what you want exactly, but there are workarounds without making things static.
You can make a function that returns the new object
function tst( $s ) {
return new tst( $s );
}
echo tst( "again" )->show();
To answer your question:
public static function create( $s )
{
return new tst($s);
}
public function show()
{
return $this->s;
}
The above will allow you to do tst::create("again")->show(). You can rename create as you like.
Agile Toolkit uses this approach everywhere. It uses add() method wrapper which is defined for global object ancestor. Here is some real-life code:
$page
->add('CRUD')
->setModel('User')
->setMasterField('admin',false);
This code creates 'CRUD' view, puts it on the page, creates and links with Model_User class instance which receives additional condition and default value for boolean 'admin' field.
It will display a CRUD control on the page with add/edit/delete allowing to edit all users except admins.
Here is code to describe concept:
class AbstractObject {
public $owner;
function add($class){
$c=new $class;
$c->owner=$this;
return $c;
}
}
class Form extends AbstractObject {
function dosomething(){
return $this;
}
}
class OtherForm extends Form {}
$object->add('Form')->dosomething()->owner
->add('OtherForm'); // etc
I think it's awesome and very practical approach.
p.s. I have to note new syntax for exceptions:
throw $this->exception('Something went bad');
using $this links exception to the object, which is at fault, which also can set default class for exception.

accessing parent class inherited variable in subclass in PHP

I have made a class in php which is goind to be inherited by another class in the other folder.
when i put echo $this->protectedvariableofclass; //in subclass function
it gives no value
remember my base class is stored \class\user.php
sublass is stored as \model\model_user.php
Please help me out
Thanks in advance
Base Class in \class\user.php
<?php
class user
{
protected $user_id;
//setter method
public function set_user_id($user_id)
{
$this->user_id=$user_id;
}
//getter method
public function get_user_id()
{
return $this->user_id;
}
}
?>
Subclass in \model\model_user.php
<?php
require_once 'class/user.php';
class model_user extends user
{
public function checkUser()
{
echo $this->user_id;
$sql = "SELECT * FROM user WHERE user_id='$this->user_id'";
$result = mysql_query($sql);
if(!result)
{
die('error'.mysql_error());
}
$duplicates = mysql_num_rows($result);
if($duplicates > 0)
return 1;
else
return 0;
}
}
Maybe you have done this already, but in case you're not, try this:
$model_user = new model_user();
$model_user->set_user_id(5);
$model_user->checkUser(); // Should output 5
Everything I see is that you're trying to output user_id which is not assigned anywhere in the posted code.

Categories