I saw this code in a PHP book (PHP architect, ZEND PHP 5 Certification guide page 141)
class foo{
public $bar;
protected $baz;
private $bas;
public var1="Test"; //String
public var2=1.23; //Numericvalue
public var3=array(1,2,3);
}
and it says
Properties are declared in PHP using one of the PPP operators, followed by their
name:
Note that, like a normal variable, a class property can be initialized while it is being
declared. However, the initialization is limited to assigning values (but not by
evaluating expressions). You can’t,for example,initialize a variable by calling a function—that’s something you can only do within one of the class’ methods (typically,
the constructor).
I can not understand how var1, var2, var3 are declared. Isn't it illegal?
The sample code is (almost) valid (it's just missing a few $ signs.)
class foo
{
// these will default to null
public $bar;
protected $baz;
private $bas;
// perfectly valid initializer to "string" value
public $var1 = "Test"; //String
// perfectly valid initializer to "float" value
public $var2 = 1.23; //Numericvalue
// perfectly valid initializer to "array" value
// (array() is a language construct/literal, not a function)
public $var3 = array(1,2,3);
}
So, the book your code comes from is definitely in error.
No, this is an error. Defining:
public var1="Test"; //String
Will give you:
Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE
For details, see http://codepad.org/meMrSmfA.
Variables in PHP are "represented by a dollar sign followed by the name of the variable". Although dollarless variables have been requested, I doubt whether they we ever see them enabled.
Point in short: your code is invalid.
In php variable are auto casting.whatever you want keep in a variable no need to declare it type .
But one mandatory thing is that when you going to declare a Variable in php you must have to use "$"
which one you missed .Book declaration is
public var1="Test"; //String
public var2=1.23; //Numericvalue
public var3=array(1,2,3);
its a wrong declaration
Right is
public $var1="Test"; //String
public $var2=1.23; //Numericvalue
public $var3=array(1,2,3);
that's other wise every thing are fine .
Thank you
Related
I know it is possible to declare the type of function parameters, function return, and class attributes. (as demonstrated below)
class HasString {
private string $value;
public function getValue() : string
{
return $value;
}
public function setAttribute(string $arg0)
{
$this->value = $arg0;
}
}
However, the following will not work.
// Tested in PHP 7.4.1
string $localVar = "value"; // Parse error: syntax error, unexpected '$localVar' (T_VARIABLE) in php shell code on line 1
Does php has a syntax that I can use to explicitly declare the type of a local variable?
This would be useful to catch bugs where a variable receives an unexpected value, and to help the IDE identify the variable type when dealing with mixed or unspecified function returns.
You can using typecasting to force a variable into a type like so:
$string = (string) 3;
You'll find $string is now the string: "3".
If you only want to allow one type (and not have any conversion/casting) the simple answer is: in PHP you cannot really do this as PHP is a weakly typed language. There are some workaround that you can read more about it in this question.
I think to just type cast your variable is a bit risky as unexpected behaviour might occur.
If you cast an int to a string that might work in a lot of cases but could also lead to not so obvious errors.
What you are looking for are PHPDoc Annotations as there is unfortunately no way to do what you do with the class properties on the local variables. You can learn more about these here https://www.phpdoc.org/ and here https://phpstan.org/writing-php-code/phpdocs-basics
But if you are using any framework it would already come with those.
Or your IDE also just supports them like for example Phpstorm or Eclipse.
Code example
public function foo(): void {
/* #var string */
$localVar;
// ... do other stuff
}
Can some one explain why this doesn't work:
private static $bundles = array(
'page-builder' => array(
'Freya\\Bundle\\PageBuilder' => self::$baseDir . '/freya-bundle-pagebuilder/Freya/Bundle/PageBuilder'
);
);
self::$baseDir is __DIR__. I thought at run time PHP would evaluate this and save it out as path/to/some/dir/freya- ....
The exact error is:
Parse error: syntax error, unexpected '$baseDir' (T_VARIABLE), expecting identifier (T_STRING) or class (T_CLASS) in /vagrant/local-dev/content/mu-plugins/Freya-MU/bundles/BundleLoader.php on line 51
Line 51, is: 'Freya\\Bundle\\PageBuilder' => self::$baseDir . '/freya-bundle-pagebuilder/Freya/Bundle/PageBuilder'
So ... What am I missing and whats the proper way to do this?
PHP Version: 5.5
PHP does not allow this. PHP properties may be initialized to constant values, but only with constant values that are available at compile time. From the manual:
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.
Whatever value your static property $baseDir holds is simply not available until the class definition is actually executed (i.e. runtime).
You can get around this to a degree by using a class constant:
class AClass {
const MY_CONSTANT = 42;
protected $property = self::MY_CONSTANT;
}
Class constants are evaluated at compile time, which is what you need to do. Note however that you cannot do any other manipulations (e.g. initialize $property to be self::MY_CONSTANT * 3)
I would suggest leaving self::$baseDir completely out of your property, and either inject it in during construction or whenever your property is actually being used.
You can't use a variable when declaring a property in a class. Check out the invalid property declarations in the PHP manual.
<?php
class SimpleClass
{
// invalid property declarations:
public $var1 = 'hello ' . 'world';
public $var2 = <<<EOD
hello world
EOD;
public $var3 = 1+2;
public $var4 = self::myStaticMethod();
public $var5 = $myVar;
This is because PHP doesn't execute any code when parsing/compiling your class.
Just in addition to the other answers really: PHP 5.5 doesn't allow expressions, including concatenation, in default value definitions, but 5.6 does. (http://php.net/manual/en/migration56.new-features.php)
So, basically, either upgrade your PHP version or set the value of $bundles from a method. There is no problem with your array otherwise.
I'm trying to insert a static variable in an array like this :
static $datas = array(
'link' => config::$link
);
But i'm having this error
Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING
I discovered PHP doc say that :
Like any other PHP static variable, static properties may only be
initialized using a literal or constant; expressions are not allowed.
So while you may initialize a static property to an integer or array
(for instance), you may not initialize it to another variable, to a
function return value, or to an object.
But I'm sure there is a way to do that, any suggestion ?
No, there is no workaround. static variables and properties can only be initialized with constant values. That means literals or constants. Variables, static or not, cannot be used, period. You have to assign a variable value later using procedural code somewhere.
Consider the following:
$var = 'foo' . 'bar'; # Not a member of a class, free-standing or in a function.
As soon as I mark $var as static, however:
static $var = 'foo' . 'bar';
PHP (5.3.1 on a WAMP setup) complains with the following error:
Parse error: syntax error, unexpected '.', expecting ',' or ';'
It seems that the string concatenation is the culprit here.
What's going on here? Can someone explain the rules for static variables to me?
The manual states, in Variables scope:
Trying to assign values to these [static] variables which are the result of expressions will cause a parse error.
There is also mention of it in Static keyword:
Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed.
Although it should be noted that a property, static or not, cannot be initialized using an expression neither.
You can not do expressions in initializers. You can, however, do this:
define('FOOBAR', 'foo'.'bar');
static $var = FOOBAR;
echo $var;
Little known fact is that even though initializers can not contain runtime expressions, it can contain constants which can be defined and resolved at runtime. The constant has to be defined by the time $var is first used though, otherwise you'll get string identical to the constant (e.g. "FOOBAR").
I do this:
class MyClass {
static $var1;
static $var2;
public static function _init() {
self::$var1 = 'slkslk' . 'sksks' . 'arbitrary' ;
self::var2 = <<<EOT
<root>
<elem1>skjsksj</elem1>
</root>
EOT;
}
}
MyClass::_init();
Here is a minimal test case I've isolated:
<?php
class What {
public $foo = range(0,5);
}
?>
I have no idea why this produces an error:
PHP Parse error: syntax error, unexpected '(', expecting ',' or ';' in TestCase.php on line 4
Using array() works.
Using PHP 5.3.3 (bundled with OS X).
You can only assign constant values in that context. You'll have to initialize your $foo in a constructor if you want to use the return value of a function.
<?php
class What {
public $foo;
public function __construct() {
$this->foo = range(0,5);
}
}
?>
BTW: As others have pointed out, array() is not a function. It's a language construct.
Array isn't a function, it's a language construct. That's why it's allowed.
Class member variables are called "properties" ... 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.
http://www.php.net/manual/en/language.oop5.properties.php
Check this link as a similar problem was sent and had been solved :-
http://www.phpbuilder.com/board/showthread.php?t=10366062
Also you can see the examples of using range() function in PHP.Net Manual although I think the problem may be in the variable $foo and public keyword as you there may be a type mismatch or a conflict beteen the version of the PHP function and your running PHP version.
I hope this answer helps you..