I have this code:
<?php
$db_initiallized = false;
$db_connection = NULL;
function db_init()
{
global $db_initiallized, $db_connection;
if(!$db_initiallized) //error occurs on this line
{
$db_connection = mysql_connect("server", "username", "password");
if(!$db_connection)
{
echo 'Connection failure!';
exit();
}
$db_initiallized = true;
}
}
?>
And I get the error:
Use of undefined constant
I'm not sure why this error is occurring. Perhaps I am declaring global variables wrong. What's going on here?
The $GLOBALS array can be used instead:
$GLOBALS['db_initiallized'] = false;
$GLOBALS['db_connection'] = NULL;
function db_init(){
echo $GLOBALS['db_initiallized'];
echo $GLOBALS['db_connection'];
}
OR
If the variable is not going to change you could use define.
define('db_initiallized', FALSE);
define('db_connection', NULL);
function db_init()
{
echo db_initiallized;
echo db_connection;
}
OR
If you have a set of functions that need some common variables, a class with properties may be a good choice instead of a global:
class MyTest
{
protected $a;
public function __construct($a)
{
$this->a = $a;
}
public function head()
{
echo $this->a;
}
public function footer()
{
echo $this->a;
}
}
$a = 'localhost';
$obj = new MyTest($a);
Related
class test() {
function get_signup($user)
{
global $hostid;
foreach ($hostname as $host)
{
$hostid = $host->id;
}
return $hostid;
}
function get_login($user)
{
global $hostid;
// get_signup($user);
echo $hostid;
}
}
Is that possible to pass a variable globally from one function to another without calling get_signup($user).
You can access the global variable from anywhere. But here you will get empty result as you are not calling get_signup($user), so $hostid is not assigned value. You can write script this way :
class test() {
private $hostid;
function get_signup($user)
{
foreach ($hostname as $host)
{
$this->hostid = $host->id;
}
return $this->hostid;
}
function get_login($user)
{
echo $this->hostid;
}
}
I am trying to get a dynamic variable value in a PHP class but not sure how to do this. Here's my code:
<?php
class Test
{
public $type = "added";
public $date_added;
public function set_status()
{
$this->date_added = "Pass";
}
public function get_status()
{
echo $this->date_{$type};
}
}
$test = new Test();
$test->set_status();
$test->get_status();
?>
I am getting following error:
Notice: Undefined property: Test::$date_ in...
Notice: Undefined variable: type in ...
If I write echo $this->date_added; in place of echo $this->date_{$type}; then I get output "Pass".
How to fix it and do it properly?
Since you're using variable variables, put them in quotes, then concatenate:
echo $this->{'date_' . $this->type};
// not $type, use `$this->` since it's part of your properties
Or using via formatted string (double quotes will work as well):
echo $this->{"date_{$this->type}"};
<?php
class Test
{
public $type = "added";
public $date_added;
public function set_status()
{
$this->date_added = "Pass";
}
public function get_status()
{
echo $this->{'date_' . $this->type};
}
}
$test = new Test();
$test->set_status();
$test->get_status();
?>
You can do it multiple ways, date_{$type} is not valid expression and to acccess the class property you have to use this keyword .
class Test
{
public $type = "added";
public $date_added;
public function set_status()
{
$this->date_added = "Pass";
}
public function get_status()
{
$prop = 'date_'.$this->type;
echo $this->{'date_'.$this->type}; # one way to do it
echo $this->$prop; # another way to do it
echo $this->{"date_{$this->type}"}; # another way to do it
}
}
$test = new Test();
$test->set_status();
$test->get_status();
I could use RefexionFunction outside of a class, but inside a class I get an exception.
Fatal error: Uncaught ReflectionException: Function Test::test_function() does not exist in test.php.
<?php
function parameters($functionName,$args){
$f = new ReflectionFunction($functionName);
....
}
class Test{
public function test_functionA($abc,$d,$e,$f) {
parameters(__METHOD__,func_get_args());
}
protected function test_functionB($abc,$d,$e,$f) {
parameters(__METHOD__,func_get_args());
}
private function test_functionC($abc,$d,$e,$f) {
parameters(__METHOD__,func_get_args());
}
}
$test = new Test();
$test->test_function('something',1,2,array(123,456));
?>
Appreciate your help.
Your error:
Fatal error: Uncaught ReflectionException: Function Test::test_function() does not exist in test.php.
Doesn't refer to the function name quite as you expect it to.
ReflectionClass docs says this:
The ReflectionClass class reports information about a class.
ref: https://secure.php.net/manual/en/class.reflectionclass.php
You want to use a combination of methods available in that class to get information about the passed method like this:
public function parameters($class, $fnc)
{
$f = new ReflectionClass($class);
if ($f->hasMethod($fnc)) {
return 'howdy folks';
} else {
return 'not so howdy folks';
}
}
You first pass the class before checking if the function exists. You can then use the built-in function hasMethod to check if the function exists. You then use the parameters function like this:
public function testFunction()
{
return $this->helper->parameters(__CLASS__, __FUNCTION__);
}
All together the code looks like this:
<?php
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
class paramsHelper
{
public function parameters($class, $fnc)
{
$f = new ReflectionClass($class);
$f->getMethod($fnc);
if ($f->hasMethod($fnc)) {
return 'howdy folks';
} else {
return 'not so howdy folks';
}
return $f;
}
}
class Test
{
protected $helper;
public function __construct($helper)
{
$this->helper = $helper;
}
public function testFunction()
{
return $this->helper->parameters(__CLASS__, __FUNCTION__);
}
}
$test = new Test(new paramsHelper());
echo '<pre>';
print_r($test->testFunction());
echo '</pre>';
One of your other problems is that __METHOD__ actually returns a string like this: Test::testFunction not testFunction - hence my use of __FUNCTION__ instead.
Edit:
To get the parameters of the passed method, change your parameters method to this:
class paramsHelper
{
public function getMethodParameters($class, $fnc)
{
$f = new ReflectionMethod($class, $fnc);
echo '<pre>';
print_r($f->getParameters());
echo '</pre>';
}
}
This uses ReflectionMethod in place of ReflectionClass - this is more inline with your intended use.
ref: https://secure.php.net/manual/en/class.reflectionmethod.php
use:
class paramsHelper
{
public function getMethodParameters($class, $fnc)
{
$f = new ReflectionMethod($class, $fnc);
echo '<pre>';
print_r($f->getParameters());
echo '</pre>';
}
}
class Test
{
protected $helper;
public function __construct($helper)
{
$this->helper = $helper;
}
public function testFunction($a = '', $b = 1, $c = 3)
{
return $this->helper->parameters(__CLASS__, __FUNCTION__);
}
}
$test = new Test(new paramsHelper());
echo '<pre>';
print_r($test->testFunction());
echo '</pre>';
How would one rewrite the following ...
class crunch {
private $funcs = [];
public function set($name, $function) {
$this->funcs[$name] = $function;
}
public function call($function, $data=false) {
if (isset($this->funcs[$function]) && is_callable($this->funcs[$function])) {
return $this->funcs[$function]($data);
}
}
}
$db = 'dbhandle';
$crunch = new crunch();
$crunch->set('myfunction', function($data) {
global $db;
echo 'db = '. $db .'<br>'. json_encode( $data );
});
$crunch->call('myfunction', [123,'asd']);
... which correctly outputs ...
db = dbhandle
[123,"asd"]
... to remove the ugly global requirement when using frequently used variables/handles within dynamically added functions?
Normally, I'd define the global on construction as follows, but this understandably fails with the fatal error Uncaught Error: Using $this when not in object context ...
class crunch {
private $db;
private $funcs = [];
public function __construct($db) {
$this->db = $db;
}
public function set($name, $function) {
$this->funcs[$name] = $function;
}
public function call($function, $data=false) {
if (isset($this->funcs[$function]) && is_callable($this->funcs[$function])) {
return $this->funcs[$function]($data);
}
}
}
$db = 'dbhandle';
$crunch = new crunch($db);
$crunch->set('myfunction', function($data) {
echo 'db = '. $this->db .'<br>'. json_encode( $data );
});
$crunch->call('myfunction', [123,'asd']);
What's the cleanest way to accomplish the goal?
EDIT: As #Rajdeep points out, I could pass $db within the $crunch->set() function. But I'd like to avoid this, since each dynamic function could reference anywhere from 0-5 of these private variables, and it would be inelegant to have to call all 5 with every $crunch->set().
Instead of creating a private instance variable $db, you could simply pass this variable to the call() method. Your code should be like this:
class crunch {
private $funcs = [];
public function set($name, $function) {
$this->funcs[$name] = $function;
}
public function call($function, $data=false, $db) {
if (isset($this->funcs[$function]) && is_callable($this->funcs[$function])) {
return $this->funcs[$function]($data, $db);
}
}
}
$db = 'dbhandle';
$crunch = new crunch();
$crunch->set('myfunction', function($data, $db){
echo 'db = '. $db .'<br>'. json_encode( $data );
});
$crunch->call('myfunction', [123,'asd'], $db);
Output:
db = dbhandle
[123,"asd"]
Update(1):
In case you want to access $db as instance variable only, the solution would be like this:
class crunch {
public $db;
private $funcs = [];
public function __construct($db) {
$this->db = $db;
}
public function set($name, $function) {
$this->funcs[$name] = $function;
}
public function call($function, $data=false) {
if (isset($this->funcs[$function]) && is_callable($this->funcs[$function])) {
return $this->funcs[$function]($this, $data);
}
}
}
$db = 'dbhandle';
$crunch = new crunch($db);
$crunch->set('myfunction', function($crunch, $data) {
echo 'db = '. $crunch->db .'<br>'. json_encode( $data );
});
$crunch->call('myfunction', [123,'asd']);
Note that you have to make $db as public member variable, otherwise it would be inaccessible while calling the set() method.
I'm running the following code:
class Foo {
private $var = 0;
function isVarSet () {
return ($this->var != 0);
}
}
...
foo = new Foo();
results in an "undefined property" notice: foo::$var on my PHP (ver. 5.3.5).
if I rewrite just the function isVarSet():
function isVarSet() {
if (isset($this->var))
return ($this->var != 0);
return false;
}
the notice disappears.
This I do not understand. $var is set in both cases, why would it be an undefined property? Why do I need to use isset() to prevent this notice? Also, why does the notice refer to $var with the scope operator :: ? I'm not using a static class, I'm using an instance foo. $foo->isVarSet() should access a $var that is both defined and non-static.
I've been working on this for hours now and read all other answers on the undefined property notice, but this one I just don't get. Please enlighten me, StackOverFlow masters.
the code in my application:
<?php
class session {
private $userId = 0;
function __construct() {
session_start();
$this->setUserId();
}
public function isLoggedIn() {
//if (isset($this->userId))
return ($this->userId != 0);
//return false;
}
function getUserId() {
if (isset($this->userId))
return $this->userId;
else
return false;
}
private function setUserId() {
if (isset($_SESSION['userId'])) {
$this->userId = $_SESSION['userId'];
} else
unset($this->userId);
}
public function login($user) {
if ($user != null) {
$_SESSION['userId'] = $user->id;
$this->userId = $user->id;
}
}
public function logout() {
unset($_SESSION['userId']);
unset($this->userId);
}
}
$session = new Session();
?>
The call to the session class is made like so:
if ($session->isLoggedIn())
redirectToLocation("../public/index.php");
(after the whole edit).
What do you think this line does (in setUserId):
unset($this->userId);
You might just want to set it to 0 as previous (which you recognize as not logged in:
$this->userId = 0;
Or:
$this->userId = null;
Take your pick.
php 5.3.5/windows
<?php
function eh($errno, $errstr) {
echo "[$errno] $errstr";
}
set_error_handler('eh');
class Foo {
private $var = 0;
function isVarSet () {
return ($this->var != 0);
}
public function testVar() {
return var_export($this->isVarSet());
}
}
$foo = new Foo();
echo $foo->testVar();
?>
output is:
false
for $var=1, output is:
true
So it works perfectly here.
I think it is because you didn't initialize your variable in your first example. You need to first initialize the var in a method which is called. Only then it is initialized.
Hope this helps you.