Beginner question.
How do I substitute:
$_SESSION['personID'] for {personID} in the following:
public static $people_address = "/v1/People/{personID}/Addresses"
look this:
$template = "/v1/People/{personID}/Addresses";
$people_address = str_replace('{personID}', $_SESSION['personID'], $template);
echo $people_address;
output:
/v1/People/someID/Addresses
EDIT: This answer no longer applies to the question after edit but I'm leaving it around for a little while to explain some questions that occured in comments another answer to this question
There are a few ways - the . operator is probably the easiest to understand, its entire purpose is to concatenate strings.
public static $people_address = "/v1/People/".$_SESSION['personID']."/Addresses";
//PHP Parse error: syntax error, unexpected '.', expecting ',' or ';'
public static $people_address = "/v1/People/$_SESSION[personID]/Addresses";
//PHP Parse error: syntax error, unexpected '"' in
However you can't use concatenation in property declarations sadly - just simple assignment. You cant use the "string replacement" format either:
To work around it you could assign the static outside of the class - i.e.:
class test {
public static $people_address;
// ....
}
// to illustrate how to work around the parse errors - and show the curly braces format
test::$people_address = "/v1/People/${_SESSION[personID]}/Addresses";
// another (much better) option:
class test2 {
public static $people_address;
public static function setup() {
self::$people_address = "/v1/People/".$_SESSION['personID']."/Addresses";
}
}
// somewhere later:
test2::setup();
Related
So I'm trying to create a page, and the software I use, uses the below code to create pages:
public function 2testnew()
{
$pagetitle = "testnew";
$this->SetVars(compact('pagetitle'));
return $this->render(dirname(__DIR__) . "/" . self::_VIEWS_PATH . "/" . self::_PAGES_DIR, __FUNCTION__, TEMPLATE_NAME);
}
Unfortunately, when I start my page name with "2" at the beginning of the page name, my website stops working, and also on Notepad++, it shows "2" in orange color, meaning there's something wrong.
I'm a beginner at PHP, so please guide me. How do I achieve a class starting with a number instead because I want to create a page that has a number at the beginning of the name?
Thank you for your help.
There's something incomplete in your error reporting settings. When properly configured you'd get something like:
Parse error: syntax error, unexpected '2' (T_LNUMBER)
Why doesn't PHP parser expect a 2 character there? Because it isn't a valid class method name. It's admittedly not documented where you'd expect it to but it can be found in the functions chapter (class methods follow the same rules as regular functions):
Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$.
If you absolutely need to, how can you? You can hack it with e.g. magic methods:
class MyController
{
private function twotestnew($one, $two)
{
echo 'Calling ', __METHOD__, '() with arguments ', $one, ' and ', $two, "\n";
}
public function __call($name, $arguments)
{
$map = [
'2testnew' => 'twotestnew',
];
$name = mb_strtolower($name);
if (isset($map[$name])) {
return call_user_func_array([$this, $map[$name]], $arguments);
}
throw new RuntimeException('Not found');
}
}
This could use many refinements but I hope you get the idea. You can test the above code with the variable functions syntax (for good or bad, the syntax doesn't apply to function definitions):
$page = new MyController();
$page->{'2testnew'}('Foo', 'Bar');
It seems like your function name is invalid. Function names in php cannot start with a number. You can read more here.
Ordinarily, one would expect that the unexpected T_STRING implies a missing semicolon. However, in this case, where's the semicolon missing from??
global $lay;
$yal = eval("return '$lay';");
echo $yal . "\n";
The error is thrown in the eval, viz
Parse error: syntax error, unexpected T_STRING in ... BOGARIP.php(140) : eval()'d code on line 1
with $lay containing
$reportDate\t$heads['Account']\t$id\t$heads['Time zone']\t$heads['Campaign']\t$heads['Ad group']\t$heads['Network']\t$heads['Network (with search partners)']\t\t$heads['Ad group state']\t$heads['Campaign state']\t$heads['Impressions']\t$heads['Clicks']\t$heads['CTR']\t$heads['Avg. CPC']\t$heads['Avg. CPM']\t$heads['Cost']\t$heads['Avg. position']
Does this imply that the bug is actually in $lay or am I missing something else? Is this level of string substitution even possible?
You really shouldn't be doing anything with eval, generally speaking. But, for the sake of the technical issue here, consider the following:
eval("return '$lay';");
You're surrounding the $lay variable with single quotes. Now let's look at the contents of this variable:
$reportDate\t$heads['Account...
See the problem? You're using single quotes within the value too. Swap out the quotes in your eval statement so there is no longer a conflict:
eval('return "$lay";');
Again again, please don't use this code. By and large, professionals will steer you away from every using eval, as it opens up your application to a great deal of potential woes. Please find another way to do whatever it is you're attempting.
Took #Evert's advice and refactored. Now the format contains
%DATE%\t%Account%\t%ID%\t%Time zone%\t%Campaign%\t%Ad group%\t%Network%\t%Network (with search partners)%\t\t%Ad group state%\t%Campaign state%\t%Impressions%\t%Clicks%\t%CTR%\t%Avg. CPC%\t%Avg. CPM%\t%Cost%\t%Avg. position%
and the code
$heads["ID"] = $id;
$heads["DATE"] = $reportDate;
...
global $lay;
$layout = $lay;
foreach ($heads as $key => $value) {
$layout = str_replace("%" . $key . "%", $value, $layout);
}
$layout = str_replace("\\n", "\n", $layout);
$layout = str_replace("\\t", "\t", $layout);
In my PHP file I have created a class as below but I am getting error on line 3rd and 5th line.
class CommonPath{
var $baseurl = 'http://mysite.com/';
var $docroot = realpath(dirname(__FILE__));
var $root = '/';
var $images = $this->root.'/img';
}
My Dreamwaver CS5 showing these lines (3rd & 5th) as erroneous lines and I am getting following error on executing this code.
Parse error: parse error, expecting `','' or `';'' in D:\wamp\www\site\libs\CommonPath.php on line 3
You can have only literals and constants as default values. No functions or other expressions are allowed.
There are two different mistakes. First, you cannot use functions to define class variables (line 3). Moreover, $this does not make sense in line 5, as you have got no object yet.
You can't assign the values like that right when you're declaring your member properties. Assign it in the constructor
class CommonPath{
var $baseurl = 'http://mysite.com/';
var $docroot = '';
var $root = '/';
var $images = '';
function __construct() {
$this->docroot = realpath(dirname(__FILE__));;
$this->images = $this->root.'/img';
}
}
You can not concat string and assign any value to variable which need to call any function, at the time declaring class variable.
I know that you can create global constants in terms of each other using string concatenation:
define('FOO', 'foo');
define('BAR', FOO.'bar');
echo BAR;
will print 'foobar'.
However, I'm getting an error trying to do the same using class constants.
class foobar {
const foo = 'foo';
const foo2 = self::foo;
const bar = self::foo.'bar';
}
foo2 is defined without issue, but declaring const bar will error out
Parse error: syntax error, unexpected '.', expecting ',' or ';'
I've also tried using functions like sprintf() but it doesn't like the left paren any more than the string concatenator '.'.
So is there any way to create class constants in terms of each other in anything more than a trivial set case like foo2?
The only way is to define() an expression and then use that constant in the class
define('foobar', 'foo' . 'bar');
class Foo
{
const blah = foobar;
}
echo Foo::blah;
Another option is to go to bugs.php.net and kindly ask them to fix this.
Imho, this question deserves an answer for PHP 5.6+, thanks to #jammin comment
Since PHP 5.6 you are allowed to define a static scalar expressions for a constant:
class Foo {
const BAR = "baz";
const HAZ = self::BAR . " boo\n";
}
Although it is not part of the question, one should be aware of the limits of the implementation. The following won't work, although it is static content (but might be manipulated at runtime):
class Foo {
public static $bar = "baz";
const HAZ = self::$bar . " boo\n";
}
// PHP Parse error: syntax error, unexpected '$bar' (T_VARIABLE), expecting identifier (T_STRING) or class (T_CLASS)
class Foo {
public static function bar () { return "baz";}
const HAZ = self::bar() . " boo\n";
}
// PHP Parse error: syntax error, unexpected '(', expecting ',' or ';'
For further information take a look at: https://wiki.php.net/rfc/const_scalar_exprs and http://php.net/manual/en/language.oop5.constants.php
Always fall back to the trusty manual for stuff like this.
Regarding constants:
The value must be a constant
expression, not (for example) a
variable, a property, a result of a
mathematical operation, or a function
call.
So... "no" would be the answer :D
For class constants, you can't assign anything other than a constant expression. Quoting the PHP manual:
"The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call. "
This may not be directly what you're looking for, but I came across this thread, so here is a solution that I used for an issue I was having (based off of #user187291's answer):
define('app_path', __DIR__ . '/../../');
const APPLICATION_PATH = app_path;
.
.
.
require_once(APPLICATION_PATH . "some_directory/some_file.php");
.
.
.
Seems to work great!
Please could someone experienced in PHP help out with the following. Somewhere in my code, I have a call to a public static method inside a non-instantiated class:
$result = myClassName::myFunctionName();
However, I would like to have many such classes and determine the correct class name on the fly according to the user's language. In other words, I have:
$language = 'EN';
... and I need to do something like:
$result = myClassName_EN::myFunctionName();
I know I could pass the language as a parameter to the function and deal with it inside just one common class but for various reasons, I would prefer a different solution.
Does this make any sense, anyone? Thanks.
Use the call_user_func function:
http://php.net/manual/en/function.call-user-func.php
Example:
call_user_func('myClassName_' . $language . '::myFunctionName');
I think you could do:
$classname = 'myClassName_' . $language;
$result = $classname::myFunctionName();
This is called Variable Functions
I would encapsulate the creation of the class you need in a factory.
This way you will have a single entry point when you need to change your base name or the rules for mapping the language to the right class.
class YourClassFactory {
private $_language;
private $_basename = 'yourclass';
public YourClassFactory($language) {
$this->_language = $language;
}
public function getYourClass() {
return $this->_basename . '_' . $this->_language;
}
}
and then, when you have to use it:
$yourClass = $yourClassFactoryInstance->getYourClass();
$yourClass::myFunctionName();
As temuri said, parse error is produced, when trying '$className::functionName' :
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM ...
In my case (static method with 2 arguments), best solutions is to use call_user_func_array with 2 arrays (as suggested by nikc.org):
$result = call_user_func_array(array($className, $methodName), array($ard1, $arg2));
BR
although i think the way you deal is a very bad idea, i think i may have a solution
$className = 'myClassName_'.$language;
$result = $className::myFunctionName();
i think this is what you want
You can easily do next:
<?php
class B {
public static $t = 5;
public static function t($h) {
return "Works!" . $h;
}
}
$g = 't';
$class = 'B';
echo $class::$g('yes'); //Works! Yes
And it will works fine, tested on PHP 5.2 >=
As far as i could understand your question, you need to get the class name which can be done using get_class function. On the other hand, the Reflection class can help you here which is great when it comes to methods, arguments, etc in OOP way.
Solutions like:
$yourClass::myFunctionName();
will not work. PHP will produce parse error.
Unfortunately, the only way is to use very slow call_user_func().
I know it's an old thread, but as of PHP 5.3.0 you should be using forward_static_call
$result = forward_static_call(array('myClassName_EN', 'myFunctionName'));
Using your $language variable, it might look like:
$result = forward_static_call(array('myClassName_' . $language, 'myFunctionName'));