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
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 wanted to have a static closure variable in my class, so that people can change the behavior of a specific part of the code. However, I can't seem to be able to initialize it anywhere.
First I tried this:
public static $logger = function($sql) { print_r($sql); };
But apparently PHP can't handle that. Ok, so I made a static init method:
public static $logger;
static function init() {
/* if (!Base::logger) */
Base::logger = function($sql) { print_r($sql); };
}
And call it at the end of the file, outside class definition. But this also give me a syntax error: Parse error: syntax error, unexpected '=' in [file] on line [line]. Any hints?
The syntax error is right where the error message tells you it is (it would have been even easier to spot if you had given us line numbers...): a missing $-sign.
Base::$logger = function (...)
In addition to that, you migth want to use self:: instead of Base::, this ensure the code will work without any additional changes if you ever rename the class
self::$logger = function (...)
You can improve this code even further, when changing the initializer to a getter that JIT-creates the closure:
private static $logger = NULL;
public static function getLogger () {
if (self::$logger === NULL) {
self::$logger = function ($sql) {print_r($sql);};
}
return self::$logger;
}
[Edit] Based on your comment on this: the clean OOP way of being able to change $logger would be to use a setter:
public static function setLogger ($closure) {
self::$logger = $closure;
}
COmbining this and the getter from above ensures that you always get the value set by the setter, and, if none has been set yet, the default value. Using the setter to set the value back to NULL makes the getter create the default again, which is anoth er plus.
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.
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');