as per title above, when I trigger the controller with a hyperlink, it does runs the controller function but I couldn't get the value of SESSION after redirect from controller. The code is as follows...
function langpref($lang){
$this->load->helper('url');
redirect(ABSOLUTE_PATH, 'location');
$this->session->set_userdata('cur_lang', 'xxx');
}
*Note: ABSOLUTE_PATH is a constant of the hyperlink, and I already load the SESSION library in the autoload file.
In my view file, I written the code as follows...
<?php echo $this->session->userdata('cur_lang');?>
and it doesn't print out the SESSION value.
First Approach: You cannot access session variables like that
<?php $ci =& get_instance(); ?>
<div>
<?php echo $ci->session->userdata('cur_lang') ?>
</div>
Second Approach: Another way you can do this is pass the session data to the view
On your controller
$data['userdata'] = $this->session->userdata;
$this->load->view('your/view', $data);
On your view
echo $userdata['cur_lang'];
Shouldn't that be:
function langpref($lang){
$this->load->helper('url');
$this->session->set_userdata('cur_lang', 'xxx');
redirect(ABSOLUTE_PATH, 'location');
}
And in your view:
<?php echo $this->session->userdata("cur_lang"); ?>
session is global variable. if you want to use it in class or function. you need to access it by passing session variable as function argument. or you need to use global command. such as;
class XXX{
public function processSession($_SESSION){
return $_SESSION['xx'];
}
}
or you could use global directive
class XXX{
public function processSession(){
global $_SESSION;
return $_SESSION['xx'];
}
}
other way is starting session in function
class XXX{
public function processSession(){
session_start();
$_SESSION['xx'] = 'aaaa';
return $_SESSION['xx'];
}
}
other way, you cannot access session variable in function or class function
Related
I'm new to oop and some lines of my code are only approximate, to indicate what I want to achieve.
I want to create a session with php within a function within a class and call it in another function.
class My_beautiful_class
{
public function index()
{
$_SESSION['ciao'] = 'ciao';
var_dump($_SESSION);
}
public function anotherfunction()
{
$this->index();
var_dump($_SESSION);
}
}
I just want to understand a concept: in this way, my code will work but, on the other end, it will execute everything it will find in my function index, in my other function anotherfunction. So, if I call two variable with the same name, I could have a problem.
I guess that in theory, I could handle the problem in another way which is that I could create a variable call sessionone for example and send it some values in with my index function:
class My_beautiful_class
{
public sessionone = [];
public function index()
{
$_SESSION['ciao'] = 'ciao';
$this->sessionone = $_SESSION['ciao'];
}
public function anotherfunction()
{
$this->sessionone;
var_dump($_SESSION);
}
}
, but I was wondering if there any way to for example call only one variable that lives in one function with my first approach.
Something like: (My code is wrong on purpose, it is only to indicate what I want to achieve)
public function index()
{
$_SESSION['ciao'] = 'ciao';
}
public function anotherfunction()
{
$this->index( $_SESSION['ciao'] );
}
}
The $_SESSION variable are what is called a Superglobal in PHP: http://php.net/manual/en/language.variables.superglobals.php This gives them a few unique traits.
First, Superglobals are accessible anywhere in your application regardless of scope. Setting the value of a superglobal key in one function will make the value accessible anywhere else in your application that you want to reference it.
Say for example we want to make a class to manage our session. That class may look something like this.
class SessionManager
{
public function __construct()
{
session_start(); //We must start the session before using it.
}
//This will set a value in the session.
public function setValue($key, $value)
{
$_SESSION[$key] = $value;
}
//This will return a value from the session
public function getValue($key)
{
return $_SESSION[$key];
}
public function printValue($key)
{
print($_SESSION[$key]);
}
}
Once we have a class to manage it a few things happen. We can use this new class to add info to the session and also to retrieve it.
Consider the following code:
$session = new SessionManager();
$session->setValue('Car', 'Honda');
echo $session->getValue('Car'); // This prints the word "Honda" to the screen.
echo $_SESSION['Car']; //This also prints the word "Honda" to the screen.
$session->printValue('Car'); //Again, "Honda" is printed to the screen.
Because of a session being a superglobal, once you set a value on the session it will be assessable anywhere in your application, either in or outside of the class itself.
You must call session_start() at the beginning of your class.
You can also start the session at the beginning of your code if you include your class like this sample
Remember that you can call the session_start only one time
I just want to ask if its possible to call variables on class to another page of the site. I have tried calling the function's name and inside the parenthesis. I included the variable found inside that function e.g:
<?php
$loadconv -> loadmsg($msgReturn);
echo $loadconv;
?>
But it didn't work.
Do you want something like this?
class Load
{
public $msgReturn;
__construct()
{
}
public function loadMsg($param)
{
$this->msgReturn = $param;
}
}
Then you could do
$loadConv = new Load();
$loadConv->loadMsg('just a string');
echo $loadConv->msgReturn; // 'just a string'
I'm writing now an app, which is supposed to be as simple as possible. My controllers implement the render($Layout) method which just does the following:
public function render($Layout) {
$this->Layout = $Layout;
include( ... .php)
}
I don't really understand the following problem: in my controller, I define a variable:
public function somethingAction() {
$someVariable = "something";
$this->render('someLayout');
}
in the php view file (same I have included in the render function) I try to echo the variable, but there is nothing. However, if I declare my action method like this:
public function somethingAction() {
global $someVariable;
$someVariable = "something";
$this->render('someLayout');
}
and in my view like this:
global $someVariable;
echo $someVariable;
it does work. Still it is annoying to write the word global each time.
How can I do this? I'd rather not use the $_GLOBAL arrays. In Cake PHP, for example, there is a method like $this->set('varName', $value). Then I can just access the variable in the view as $varName. How is it done?
From the PHP Manual on include:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.
When you do
public function somethingAction() {
$someVariable = "something";
$this->render('someLayout');
}
the $someVariable variable is limited to the somethingAction() scope. Calling your render() method will not magically make the variable available in render(), because the render() method has it's own variable scope. A possible solution would be to do
public function somethingAction() {
$this->render(
'someLayout',
array(
'someVariable' => 'something'
)
);
}
and then change render() to
public function render($Layout, array $viewData) {
$this->Layout = $Layout;
include( ... .php)
}
You will then have access to $viewData in the included file, given that you are not trying to use it in some other function or method, e.g. if your included file looks like this:
<h1><?php echo $viewData['someVariable']; ?></h1>
it will work, but if it is looks like this:
function foo() {
return $viewData['someVariable'];
}
echo foo();
it will not work, because foo() has it's own variable scope.
However, a controller's sole responsibility is to handle input. Rendering is the responsibility of the View. Thus, your controller should not have a render() method at all. Consider moving the method to your View class and then do
public function somethingAction() {
$view = new View('someLayout');
$view->setData('someVariable', 'something');
$view->render();
}
The render() method of your View object could then be implemented like this:
class View
…
$private $viewData = array();
public function setData($key, $value)
{
$this->viewData[$key] = $data;
}
public function render()
{
extract($this->viewData, EXTR_SKIP);
include sprintf('/path/to/layouts/%s.php', $this->layout);
}
The extract function will import the values of an array in the current scope using their keys as the name. This will allow you to use data in the viewData as $someVariable instead of $this->viewData['someVariable']. Make sure you understand the security implications of extract before using it though.
Note that this is just one possible alternative to your current way of doing things. You could also move out the View completely from the controller.
Using global you're implicitly using the $_GLOBALS array.
A not recommended example, because globals are never a good thing:
function something() {
global $var;
$var = 'data';
}
// now these lines are the same result:
echo $_GLOBALS['var'];
global $var; echo $var;
Why don't you use simply the $this->set function?
public function render($Layout) {
$this->Layout = $Layout;
include( ... .php)
}
public function somethingAction() {
$this->set('someVariable', "something");
$this->render('someLayout');
}
// in a framework's managed view:
echo $someVariable;
I'm sorry not to know your framework in detail, but that makes perfectly sense.
Actually how it's done: There is a native extract function, that loads an associative array into the current symbol table:
array( 'var0' => 'val0', 'var1' => 'val1')
becomes
echo $var0; // val0
echo $var1; // val1
That's most likely 'what happens'.
I have a template class which goes like this:
class Template{
public $pageTitle = "";
public function __construct($pageTitle){
$this->pageTitle = $pageTitle;
}
public function display(){
include "/includes/head.php";
include "/includes/body.php";
}
}
Now, I'm used to Java's workings but I don't understand why I'm getting an undefined variable ($pageTitle) error. The included files need to be able to access that variable. I know it's going to be very simple but I actually haven't found out why.
What do I need to do to allow includes to see this variable?
The includes will also have to use $this->pageTitle. Effectively, the include makes them part of the method body.
The included file lives in the same scope as your object. So you need to call:
$this->pageTitle
If you don't want to do the whole $this->, you can do something like the following... The extract function will extract the array $this->data into variables with names respective to the key/index of each item. So now you will be able to do echo $pageTitle;
class Template{
public $data = Array();
public function __construct($pageTitle){
$this->data['pageTitle'] = $pageTitle;
}
public function display(){
extract($this->data);
include "/includes/head.php";
include "/includes/body.php";
}
}
Scope is a little different in PHP than in java.
For your specific case you need
$this->pageTitle
To access a variable declared outside the class, you'll need to make it global
global $myVar;
Below code works fine:
<?php session_start();
$_SESSION['color'] = 'blue';
class utilities
{
public static $color;
function display()
{
echo utilities::$color = $_SESSION['color'];
}
}
utilities::display(); ?>
This is what I want but doesn't work:
<?php session_start();
$_SESSION['color'] = 'blue';
class utilities {
public static $color = $_SESSION['color']; //see here
function display()
{
echo utilities::$color;
} } utilities::display(); ?>
I get this error: Parse error: syntax error, unexpected T_VARIABLE in C:\Inetpub\vhosts\morsemfgco.com\httpdocs\secure2\scrap\class.php on line 7
Php doesn't like session variables being stored outside of functions. Why? Is it a syntax problem or what? I don't want to have to instantiate objects because for just calling utility functions and I need a few session variables to be stored globally. I do not want to call a init() function to store the global session variables every time I run a function either. Solutions?
In a class you can use SESSION only in methods...
Actually, if you want to do something in a class, you must code it in a method...
A class is not a function. It has some variables -as attributes- and some functions -as method- You can define variables, you can initialize them. But you can't do any operation on them outside of a method...
for example
public static $var1; // OK!
public static $var2=5; //OK!
public static $var3=5+5; //ERROR
If you want to set them like this you must use constructor... (but remember: constructors aren't called until the object is created...)
<?php
session_start();
$_SESSION['color'] = 'blue';
class utilities {
public static $color;
function __construct()
{
$this->color=$_SESSION['color'];
}
function display()
{
echo utilities::$color;
}
}
utilities::display(); //empty output, because constructor wasn't invoked...
$obj=new utilities();
echo "<br>".$obj->color;
?>
From the PHP manual:-
Like any other PHP static variable,
static properties may only be
initialized using a literal or
constant; expressions are not allowed.
So while you may initialize a static
property to an integer or array (for
instance), you may not initialize it
to another variable, to a function
return value, or to an object.
You say that you need your session variables to be stored globally? They are $_SESSION is what is known as a "super global"
<?php
class utilities {
public static $color = $_SESSION['color']; //see here
function display()
{
echo $_SESSION['color'];
}
}
utilities::display(); ?>