PHP - Unexpected Global, expecting String in class
In my class (Which is actually a CakePHP model) I'm trying to simply set a variable and then access it from inside a function but I'm getting the following error:
Parse error: syntax error, unexpected T_GLOBAL, expecting T_FUNCTION in /path/to/file/file.php on line 120
L开发者_JAVA技巧ine 120 onwards of my file is as follows:
global $accessid = 'accessid';
global $secret = "secret";
global $b = 0;
global $m = 0;
function generateCredentials() {
global $accessid;
return $accessid;
}
Any idea where I'm going wrong? Thanks!
I'll guess that this is within a class definition like:
class Foo {
global $var;
}
You can't use this keyword there. The only keywords you can precede class properties with are the visibility declarations var
, public
, protected
and private
. Class properties are always properties of the class they're defined in, they cannot be global variables.
If you insist, you could get them from global
within a function and set them to the properties:
class Foo {
public $var;
public function foo() {
global $var;
$this->var = $var;
}
}
This is all extremely ugly though, especially since Cake gives you better tools to deal with these things, like the Configure
class to register values globally.
Or you probably just want to create simple class properties:
class Foo {
public $accessid = 'accessid';
public $secret = "secret";
public $b = 0;
public $m = 0;
function generateCredentials() {
$this->accessid;
}
}
It's not entirely clear from your question what the context is.
Free code (If this code is free-standing)
You don't use the global
keyword to define globals. Just declare them in the global scope.
$accessid = 'accessid';
$secret = "secret";
$b = 0;
$m = 0;
function generateCredentials() {
global $accessid;
return $accessid;
}
Class members (If your code is found inside a class definition)
If you want to be able to access global variables from inside a class:
$accessid = 'accessid';
$secret = "secret";
$b = 0;
$m = 0;
class X {
function generateCredentials() {
global $accessid;
return $accessid;
}
}
Or if you want class members, not globals:
class X {
public $accessid = 'accessid';
public $secret = "secret";
public $b = 0;
public $m = 0;
function generateCredentials() {
return $accessid;
}
}
Notice that you need to specify member visibility in the latter example. Take a look at the manual.
There is no global
only inside of classes/functions.
In PHP constants are global, example:
define('ACCESSID', '123456');
// inside the function ACCESSID is now available
function generateCredentials() {
echo ACCESSID;
}
I'd suggest this
private $accessid;
private $secret;
private $b;
private $m;
function generateCredentials() {
global $accessid;
global $secret;
global $b;
global $m;
$this->accessid = $accessid;
$this->secret = $secret;
$this->b = $b;
$this->m = $m;
return $accessid;
}
精彩评论