I'm developing a class and I have this structure:
class userInfo {
public $interval = 60;
public $av_langs = null;
public $ui_ip = $_SERVER['REMOTE_ADDR'];
public $ui_user_agent = $_SERVER['HTTP_USER_AGENT'];
public $ui_lang = null;
public $ui_country = null;
// non-relevant code removed
}
But when executing the script I get this error:
Parse error: syntax error, unexpected T_VARIABLE in
D:\web\www\poll\get_user_info\get_user_info.php on line 12
When I changed the 2 $_SERVER vars to simple strings the error disappeared.
So what's the problem with $_SERVER in declaring class properties?
Thanks
Use this code as a guide:
public function __construct() {
$this->ui_ip = $_SERVER['REMOTE_ADDR'];
$this->ui_user_agent = $_SERVER['HTTP_USER_AGENT'];
}
Property can be declared only with value, not expression.
You can create __construct() method, where you can initialize properties in any way.
So what's the problem with $_SERVER in declaring class properties?
You can't preset class properties with variables nor with function calls.
Here is some in-depth discussion on why: Why don't PHP attributes allow functions?
The bottom line however is, it's simply not possible.
Related
Configuration of a project in dev mode with WAMP.
PHP vers 5 and 7 are available.
Just trying to set the project root using filter_input. Could someone please explain why filter input for the protected and private vars inside the class reports a PARSE ERROR? However if used outside the class or inside a function of the class it works.
Is there a better way to do this so that it can be used globally? I find this is called a lot and would prefer to do it once.
$test = filter_input(INPUT_SERVER,'DOCUMENT_ROOT');
echo $test; //good
class FooBar{
protected $_test = filter_input(INPUT_SERVER,'DOCUMENT_ROOT'); //bad - Parse error: syntax error, unexpected '(', expecting ',' or ';'
private $_test2 = filter_input(INPUT_SERVER,'DOCUMENT_ROOT'); //bad - Parse error: syntax error, unexpected '(', expecting ',' or ';'
function __construct() {
}
public function getProducts(){
include_once
(filter_input(INPUT_SERVER,'DOCUMENT_ROOT').'/obj/user.php'); //good
}
}
You can not directly assign a function return value to a property in the class definition.
This is because the function could return different return values, and the class is only a blueprint which you must instantiate as an object to use.
For the objects that are created from your class definition you can initialize any property in the constructor:
class FooBar {
protected $var = null;
private $var2 = null;
function __construct() {
$this->var = func1();
$this->var2 = func2();
}
}
// no parse error
Despite of that, why do you use filter_input on an internal constant? You only need to filter input from the outside, i.e. GET/POST/SESSION content (user input), input read from files, from external APIs etc. But you don't need to use that on internal constants like the DOCUMENT_ROOT:
class FooBar {
private $_docroot = $_SERVER['DOCUMENT_ROOT'];
}
// no parse error
I have following code
class DataMapperFactoryBeta
{
static private $configClassName = 'ConfigBeta';
static private $client;
static private $mapper = [];
static public function initClient()
{
$className = 'Models\\DataMappers\\Clients\\'.self::$configClassName::$db_type;
}
}
The Interpretor throws me a fatal error: 'incorrect access to static class member'. I wish to have the config class name accessed dynamicly, because I will change it in the future and I don't wanna change it in many places in the code, only once, through $configClassName. Is this even possible with statics?
Split your line into two, and it should work for you as you expect:
$className = 'Models\\DataMappers\\Clients\\' . self::$configClassName;
$className = $className::$db_type;
On a side note, I couldn't find in the PHP docs whether the scope resolution operator (::) is left or right associative. It could be it's trying to interpret the line as follows:
('Models\\DataMappers\\Clients\\'.self::($configClassName::$db_type));
Without an update from the docs the code is ambiguous as to what exactly should be happening the way you have it written.
I am expecting this to be a basic syntax error I overlooked, but I can't figure it out.
In a PHP script, I keep getting the following error.
Parse error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION in [path]/scripts/users/database_connection.php on line 4
This occurs when my script to connect to the database is called with an include_once(). I stripped my script down to the most basic code (leaving in what is required by other code), and it still is calling this error.
<?php
class UserDatabaseConnection
{
$connection = sqlite_open("[path]/data/users.sqlite", 0666);
public function lookupUser($username)
{
// rest of my code...
}
}
$udb = new UserDatabaseConnection;
?>
I have struggled with this for a while, and just wondered if anyone else could spot somewhere I went wrong.
You can not put
$connection = sqlite_open("[path]/data/users.sqlite", 0666);
outside the class construction. You have to put that line inside a function or the constructor but you can not place it where you have now.
You cannot use function calls in a class construction, you should initialize that value in the constructor function.
From the PHP Manual on class properties:
This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
A working code sample:
<?php
class UserDatabaseConnection
{
public $connection;
public function __construct()
{
$this->connection = sqlite_open("[path]/data/users.sqlite", 0666);
}
public function lookupUser($username)
{
// rest of my code...
// example usage (procedural way):
$query = sqlite_exec($this->connection, "SELECT ...", $error);
// object oriented way:
$query = $this->connection->queryExec("SELECT ...", $error);
}
}
$udb = new UserDatabaseConnection;
?>
Depending on your needs, protected or private might be a better choice for $connection. That protects you from accidentally closing or messing with the connection.
Use access modifier before the member definition:
private $connection;
As you cannot use function call in member definition in PHP, do it in constructor:
public function __construct() {
$this->connection = sqlite_open("[path]/data/users.sqlite", 0666);
}
put public, protected or private before the $connection.
check that you entered a variable as argument with the '$' symbol
We should keep our content inside public/private functions only. We can keep content outside of a function.
I'm translating an application written in Laravel 4.
When I tried to translate a line in a library file, I got an error, and after some time, I figured you can't set the translation directly to a variable in a library file.
The following lines
class Service {
private $test = trans('general.name');
produces the following
syntax error, unexpected '(', expecting ',' or ';'
pointing at the "private $test" line.
I'd like to add that I can normally translate and set to a variable if it's in a function, or in a different kind of file, i.e. a view.
Does anyone have an answer to this?
You can't use a function in a class variable. You should do something like:
<?php
class Service {
private $test;
public function __construct()
{
$this->test = trans('general.name');
}
}
class Service {
private $name;
public function __construct()
{
$this->name = trans('general.name');
}
public static function test() {
$service = new Service;
return $service->name;
}
}
Here your static solution:
echo Service::test();
It is not perfect solution but can be useful in some cases
T_PAAMAYIM_NEKUDOTAYIM sounds really exotic, but most certainly absolutely nonsense to me. I traced it all down to this lines of code:
<?php
Class Context {
protected $config;
public function getConfig($key) { // Here's the problem somewhere...
$cnf = $this->config;
return $cnf::getConfig($key);
}
function __construct() {
$this->config = new Config();
}
}
?>
In the constructor I create a Config object. Here's the class:
final class Config {
private static $instance = NULL;
private static $config;
public static function getConfig($key) {
return self::$config[$key];
}
public static function getInstance() {
if (!self::$instance) {
self::$instance = new Config();
}
return self::$instance;
}
private function __construct() {
// include configuration file
include __ROOT_INCLUDE_PATH . '/sys/config/config.php'; // defines a $config array
$this->config = $config;
}
}
No idea why this doesnt work / what the error means...
T_PAAMAYIM_NEKUDOTAYIM is the double colon scope resolution thingy PHP uses - ::
Quick glance at your code, I think this line:
return $cnf::getConfig($key);
should be
return $cnf->getConfig($key);
The first is the way to call a method statically - this code would be valid if $cnf contained a string that was also a valid class. The -> syntax is for calling a method on an instance of a class/object.
Just my two cents for future visitors who have this problem.
This is the correct syntax for PHP 5.3, for example if you call static method from the class name:
MyClassName::getConfig($key);
If you previously assign the ClassName to the $cnf variable, you can call the static method from it (we are talking about PHP 5.3):
$cnf = MyClassName;
$cnf::getConfig($key);
However, this sintax doesn't work on PHP 5.2 or lower, and you need to use the following:
$cnf = MyClassName;
call_user_func(array($cnf, "getConfig", $key, ...otherposibleadditionalparameters... ));
Hope this helps people having this error in 5.2 version (don't know if this was openfrog's version).
In your example
return $cnf::getConfig($key)
Probably should be:
return $cnf->getConfig($key)
And make getConfig not static
if you still need to use the double-colon then make sure your on PHP 5.3+
The error is down to an "inappropriate use" of the double colon operator:
return $cnf::getConfig($key);
as by using the :: you're attempting to call a static method of the class itself. In your example you want to call a non-static method on an instantiated object.
I think what you want is:
return $cnf->getConfig($key);
According to wikipedia, it means a "double colon" scope resolution operator.
http://en.wikipedia.org/wiki/Scope_resolution_operator
It's the name for the :: operator
Wikipedia
For anyone using Laravel. I was having the same error on Laravel 7.0. The error looked like this
syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM), expecting ';' or ','
It was in my Routes\web.php file, which looked like this
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
use // this was an extra **use** statement that gave me the error
Route::get('/', function () {
return view('save-online.index');
})->name('save-online.index');