php how to: save session variable into a static class variable - php

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(); ?>

Related

Is there a reason for dynamic variables to not be private?

It's possible to extend classes during runtime, and I've been playing around with it a bit, but then I stumbled upon this, which to me is strange. If I define a new variable in a private function it becomes a public variable. Shouldn't it at least be protected?
Here's the code that I've used to test this:
class FooBar {
public function FooBar() {
$this->t();
}
public function createVariable() {
$this->NewVar();
}
private function NewVar() {
$this->iam = "Hello you!";
}
private function t() {
$this->T = "ballad";
return $this->T;
}
}
$fb = new FooBar();
echo $fb->T;
echo "<br/>";
var_dump($fb);
$fb->createVariable();
echo $fb->iam;
echo "<br/>";
var_dump($fb);
echo "<br/>";
$fb->outer = "okay";
echo $fb->outer;
And as an extra, since it's possible to extend a class during runtime why isn't this possible:
function foo() {
private $this->anewvar = 0; //private is illegal.
}
PHP allows variables to be instantiated at any time without explicitly defining them.
But since you haven't defined the variable explicitly, PHP doesn't know how you want it to be scoped, and it has no way for you to tell it either, so it just goes with the safest possible option and makes it public.
If you want it scoped privately, define it as a private variable in the class definition.

PHP - class forget set variables

I try to create some sort of setup class, like global values for the page.
The PHP-code
class globals
{
public $page;
public function __construct()
{
}
public function set_page($value)
{
$this->page = $value; // Maybe from a database
}
}
class get
{
public function page()
{
$globals = new globals();
return $globals->page;
}
}
$globals = new globals();
$globals->set_page('My value');
echo get::page(); // Short function to be in a template
Question
My class forget the value I set. Why is that?
Do I have to use global variables?
Is this the correct approach for the problem?
The variable is set on an object, not on a class.
For each class, you can instantiate multiple objects. Each of those have their own variable scope.
Edit:
I forgot to include the easiest, and least verbose solution to your problem. AFAIK, you're looking for a way to check what page you're on. Constants will do just that:
defined('MY_CURRENT_PAGE') || define('MY_CURRENT_PAGE','My Value');
//use anywhere like so:
echo 'Currently on page: '.MY_CURRENT_PAGE;
My class forget the value I set. Why is that?
Quite simple: your page member function isn't static, yet you call it as though it is: get::page(). Even if you were to fix this, you're creating a new instance in the page method, but you're not preserving a reference too it anywhere, so each page call will create a new globals instance, that has nothing set.
Do I have to use global variables?
No, unless you're Really desperate, never use globals
Is this the correct approach for the problem?
No, if it doesn't work, it's not correct (IMHO).
Well, what is, you might ask. There are several ways to go about this:
class globals
{
public static $page = null;//make this static, meaning all instances will share this var
public function set_page($value)
{
self::$page = $value; // Maybe from a database
}
}
class get
{
private $_globalsInstance = null;
public function __construct(globals $instance = null)
{
$this->_globalsInstance = $instance;
}
private function _getGlobals()
{
if (!$this->_globalsInstance instanceof globals)
{
$this->_globalsInstance = new globals();
}
return $this->_globalsInstance;
}
public function page()
{
return $this->_getGlobals()::$page;
}
}
Personally, however, I wouldn't work like this, I'd just pass my instances to wherever I need them (as arguments to functions/methods or just instantiate them in a scope that will be accessible:
class globals
{
public $page = null;//make this static, meaning all instances will share this var
public function set_page($value)
{
$this->page = $value; // Maybe from a database
}
}
$page = new globals();
$page->set_page('foobar');
someFunction($page);
$someObject->renderPage($page);
require_once('specificScript.php');
//inside required script:
echo $page->page;
Do I have to use global variables?
Not, if your can use PHP 5.3
Is this the correct approach for the problem?
Better to use a generic class for this, or use static properties of objects
<?php
class globals
{
public static $page;
public function __construct()
{
}
public function set_page($value)
{
self::$page = $value; // Maybe from a database
}
}
class get
{
public static function page()
{
return globals::$page;
}
}
$globals = new globals();
$globals->set_page('My value');
echo get::page(); // Short function to be in a template
P.S.
But this is not a nice approach
$globals there
class get
{
public function page()
{
$globals = new globals();
return $globals->page;
}
}
and there
$globals = new globals();
$globals->set_page('My value');
are different inctances of globals class.
One of the solutions is to make $page var static
public static $page;
I hope this helps
UPD:
Also you might apply Singleton to globals class and request for its insnance instead of creating new one directly:
globals::getInstance()->setPage('Page');
and
return globals::getInstance()->getPage();
In this case $page doesn't have to be static.
I'm not sure the other answers are very clear. You have created 2 classes. As such they have different scopes. As writen you can't access the original variable $page from the get class because it's outside the scope. Your page function in fact creates a new version of the object $globals without $page set. Normally you would place both your set and get functions in the initial object/class. Though it would be possible to use two class by calling the first class from the second and setting the page. Why you would want to do that I'm not sure.
if I were writing the class it would look like this.
class globals
{
public $page;
public function __construct()
{
}
public function set_page($value)
{
$this->page = $value; // Maybe from a database
}
public function get_page()
{
return $this->page;
}
}
Actually I would probably set page to private not public. As public I guess you don't need a get function.
for using methods of the class without object you must use static definition. but anyway you put value for one class object and try to get it from another...
Perhaps this will help you continue on your coarse:
class globals
{
public static $page;
public function set_page($value)
{
self::$page = $value; // Maybe from a database
}
}
class get extends globals
{
public function page()
{
$globals = new globals();
return parent::$page;
}
}
$globals = new globals();
$globals->set_page('My value');
echo get::page();
?>

how can i include php file in php class

i have php with an array i.e
$var = array(
"var" => "var value",
"var2" => "var value1"
);
and have another file with a class i.e
class class1{
function fnc1(){
echo $var['var2'];
//rest of function here
}
}
now how can i get $var['var'] in class file in function fnc1()
You can pass it as an argument, or use the global keyword to put it in the current scope.
However, using global is discouraged, try passing it as an argument.
Pass it as an argument?
class class1{
function fnc1($var) {
echo $var['var2'];
}
}
And in your other file call this class method with your array as an argument.
From: http://php.net/manual/en/function.include.php
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.
So you could do
class class1
{
function fnc1()
{
include 'thefile.php'
echo $var['var2'];
//rest of function here
}
}
but like others pointed out before, you dont want to do that, because it introduces a dependency on the filesystem in your class. If your method requires those variables to work, then inject them as method arguments or pass them into the constructor and make them a property (if you need them more often). This is called Dependency Injection and it will make your code much more maintainable in the long run, e.g. do
class class1
{
private $data;
public function __construct(array $var)
{
$this->data = $var;
}
function fnc1()
{
echo $this->data['var2'];
//rest of function here
}
}
and then do
$obj = new class1($var);
echo $obj->fnc1();
or require the data to be passed into the method on invocation
class class1
{
function fnc1(array $var)
{
echo $var['var2'];
//rest of function here
}
}
and then
$obj = new class1;
$obj->fnc1($var);
You might use global $var in your included file, but it's really a bad practice, as another script, before your included file, might redefine the value/type of $var.
Example :
class class1{
function fnc1(){
global $var;
echo $var['var2'];
//rest of function here
}
}
A better solution, is to pass your $var as a parameter to your fnc1(), even to your class1::__construct()
#Vindia: I'd prefer the argumant-style too, but would recommend either using type hint or a simple check to avoid warnings when accessing *non_array*['var2']:
// acccepts array only. Errors be handled outside
function fnc1(Array $var) {
echo $var['var2'];
}
// accepts any type:
function fnc1(Array $var) {
if (is_array($var)) {
echo $var['var2'];
}
}
class class1{
function fnc1(){
include 'otherFile.php';
echo $var['var2'];
//rest of function here
}
}

Why won't the shuffle function work in a PHP class?

Why won't it shuffle the array so I get a random result each time?
class greeting {
public $greet = array('hi','hello');
shuffle($greet);
}
$hi = new greeting;
echo $hi->greet[1];
Is their something wrong with my code?
If you change it so the shuffle is inside the constructor it should work fine.
class greeting {
public $greet = array('hi','hello');
function __construct(){
shuffle($this->greet);
}
}
any calculation can not be executed outside the method, inside class.
class greeting {
public $greet = array('hi','hello');
function __construct()
{
shuffle($this->greet);
}
}
$hi = new greeting;
echo $hi->greet[1];
Inside a class block you can only define constants, properties (both with fixed values) and methods. You can't put code in that block, code can only be placed inside methods (AKA functions).

C-style Variable initialization in PHP

Is there such a thing as local, private, static and public variables in PHP? If so, can you give samples of each and how their scope is demonstrated inside and outside the class and inside functions?
I don't know about C++ but there's how PHP works about:
For Function scopes:
<?php
$b = 6;
function testFunc($a){
echo $a.'-'.$b;
}
function testFunc2($a){
global $b;
echo $a.'-'.$b;
}
testFunc(3);
testFunc2(3);
?>
The output is
3-
3-6
Code inside functions can only be accessed variables outside functions using the global keyword. See http://php.net/manual/en/language.variables.scope.php
As for classes:
<?php
class ExampleClass{
private $private_var = 40;
public $public_var = 20;
public static $static_var = 50;
private function classFuncOne(){
echo $this->private_var.'-'.$this->public_var; // outputs class variables
}
public function classFuncTwo(){
$this->classFuncOne();
echo $private_var.'-'.$public_var; // outputs local variable, not class variable
}
}
$myobj = new ExampleClass();
$myobj->classFuncTwo();
echo ExampleClass::$static_var;
$myobj->classFuncOne(); // fatal error occurs because method is private
?>
Output would be:
40-20
-
50
Fatal error: Call to private method ExampleClass::classFuncOne() from context '' in C:\xampp\htdocs\scope.php on line 22
One note to take: PHP does not have variable initialization, although variables are said to be set or not set. When a variable is set, it has been assigned with a value. You can use the unset to remove the variable and its value. A not set variable is equivalent to false, and if you use it with all errors output, you will see a E_NOTICE error.
In PHP there are static, local, private, public, and protected class variables.
However, in the PHP OOP implementation things are a little different: the manual will help you:
The visibility of a property or method
can be defined by prefixing the
declaration with the keywords public,
protected or private.
Furthermore, have a look at the static keyword documentation.
You'll be able to read more about normal variables and their scope here: http://php.net/manual/en/language.variables.scope.php:
For the most part all PHP variables only have a single scope.
I hope the links will be able to explain it to you better than I did ;-)
yes, PHP 5 incldude static variables and visibility in class.
class MyClass
{
public static $my_static = 'foo';
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';
public function staticValue() {
return self::$my_static;
}
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private

Categories