Why is not possible to initialize a property to a function when you declare the property in php? The following snippit results in a Parse error: syntax error, unexpected T_FUNCTION
<?php
class AssignAnonFunction {
private $someFunc = function() {
echo "Will Not work";
};
}
?>
Yet you can initialize a property to a string, number or other data types?
Edit:
But I can assign a function to a property in the __construct() method. The following does work:
<?php
class AssignAnonFunctionInConstructor {
private $someFunc;
public function __construct() {
$this->someFunc = function() {
echo "Does Work";
};
}
}
?>
Because it is not implemented in PHP.
http://www.php.net/manual/en/language.oop5.properties.php. Quote:
They (properties) are defined by using one of the
keywords public, protected, or
private, followed by a normal variable
declaration. 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.
You cannot initialize properties like this, functions are not constant values. Hence my original answer "it is not implemented".
Why is it not implemented? That I can only guess - it probably is quite a complex task and nobody has stepped up to implement it. And/or there may not be enough demand for a feature like that.
Closures do not exist in PHP until PHP 5.3 (the latest version). Make sure you have PHP 5.3 if you want to do this.
In earlier versions, you can sort of duplicate this functionality with the create_function() function, somewhat like this:
$someFunc = create_function($args,$code);
$someFunc();
Where $args is a string formatted like "$x,$y,$z" and $code is a string of your PHP code.
Related
Alright so I think this may be extremely basic, but it has me stumped nonetheless. Before I get to my question, let me demonstrate the concept my question is based on with this working example:
<?php
$a = 'Stack';
$b = $a.' Overflow';
echo $b; // Result: "Stack Overflow"
?>
In the above example, $b is defined as the combination of $a and ' Overflow'.
Now, let's assume I want to do the same thing as above except I don't want to use global variables. I want to use classes. This is how I have attempted to achieve that:
<?php
class ClassName {
public $a = 'Stack';
public $b = $this->a.' Overflow'; // This gives me: "Parse error: syntax error, unexpected '$this'"
}
$instantiate = new ClassName;
echo $instantiate->$b; // Desired result: "Stack Overflow"
?>
As stated, this attempt results in an error. To me, this attempt seems logical, but I guess PHP doesn't think so.
Question: Is this possible, and if so, how do I go about achieving the desired result? Also, if you could explain why my attempt has failed (logically), that would be a bonus.
I've searched and researched for hours on end trying to find an answer or figure this out on my own, but for the life of me, I cannot find anyone or anything that even touches on this (including other Stack Overflow threads). I can't even find anywhere saying it's impossible or anything of the sort either.
I'm a PHP novice, so I may need more explanation than others, but any kind of help or general guidance would be much appreciated. Thank you.
You cannot use $this when defining the class because it refers to a concrete object context which becomes available after instantiation. You can use a constructor for that kinds of stuff.
class ClassName
{
public $a = 'Stack';
public $b = "";
function __construct()
{
$this->b = $this->a.' Overflow';
}
}
$instantiate = new ClassName;
echo $instantiate->b;
Quoting from the PHP Docs about defining class properties
They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. 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.
(my emphasis)
Concatenation cannot be evaluated at compile time, only at run time.
If you need to do this, then define the initial value for the property in the constructor
This would throw a syntax error because you are using $this in a scope that it is not allowed to:
The pseudo-variable $this is available inside any class method when that method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).
This means, even if you wanted you won't be able to do what you want to do because of such restriction. This is a common restriction that is in many programming languages, properties have to be initialized to static values. To solve your issue you can do any of the following:
In your constructor, create those variables.
Create the second variable on its own, and create a method that concatenates the two.
Create a magic method to do it for you.
The same restriction holds true for static class properties.
Why is not possible to initialize a property to a function when you declare the property in php? The following snippit results in a Parse error: syntax error, unexpected T_FUNCTION
<?php
class AssignAnonFunction {
private $someFunc = function() {
echo "Will Not work";
};
}
?>
Yet you can initialize a property to a string, number or other data types?
Edit:
But I can assign a function to a property in the __construct() method. The following does work:
<?php
class AssignAnonFunctionInConstructor {
private $someFunc;
public function __construct() {
$this->someFunc = function() {
echo "Does Work";
};
}
}
?>
Because it is not implemented in PHP.
http://www.php.net/manual/en/language.oop5.properties.php. Quote:
They (properties) are defined by using one of the
keywords public, protected, or
private, followed by a normal variable
declaration. 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.
You cannot initialize properties like this, functions are not constant values. Hence my original answer "it is not implemented".
Why is it not implemented? That I can only guess - it probably is quite a complex task and nobody has stepped up to implement it. And/or there may not be enough demand for a feature like that.
Closures do not exist in PHP until PHP 5.3 (the latest version). Make sure you have PHP 5.3 if you want to do this.
In earlier versions, you can sort of duplicate this functionality with the create_function() function, somewhat like this:
$someFunc = create_function($args,$code);
$someFunc();
Where $args is a string formatted like "$x,$y,$z" and $code is a string of your PHP code.
Inside a class I have 2 associative arrays. I am trying to call elements from one array to be used in another (kind of master) array.
I would like to ask whether the following can be done, or can't, or what I'm doing so wrong;
Please note, the arrays are examples.
class ProductData {
private $texture = [0=>'Cream', 1=>'Powder', 2=>'Liquid', 3=>'Paste', 4=>'Solid'];
private $food = ['type'=>'Pasta', 'info'=>[1=>'750gm', 2=>'$4.50', 3=>$this->texture[4]],
'type'=>'Soup', 'info'=>[1=>'500ml', 2=>'$7.60', 3=>$this->texture[2]]];
// Constructor, Function(s) to access the $food array...
}
Well I have found out the hard way that this cannot be done. I receive a syntax error;
syntax error unexpected '$this' (T_VARIABLE).
If I replace the $this with $texture, I receive the same error;
syntax error unexpected '$texture' (T_VARIABLE).
I'm thinking that this cannot be done, or I'm doing something very wrong, or both.
If this can be done, any assistance is very much appreciated.
Thanks,
njc
class ProductData {
private $texture;
private $food;
function __construct(){
$this->texture = [0=>'Cream', 1=>'Powder', 2=>'Liquid', 3=>'Paste', 4=>'Solid'];
$this->food = ['type'=>'Pasta', 'info'=>[1=>'750gm', 2=>'$4.50', 3=>$this->texture[4]],
'type'=>'Soup', 'info'=>[1=>'500ml', 2=>'$7.60', 3=>$this->texture[2]]];
//other construct stuff
}
}
You can only use constant values to define property values outside class methods. So in your case, you cannot use the $this variable, as it references the current object instance.
You should move the initialisation to the __construct (which is really what is meant to be for)
Check out the documentation:
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.
Here is my class
class Databases {
public $liveresellerdb = new Database('1host1','user','pswd','db');
}
the error i am getting is
Parse error: syntax error, unexpected T_NEW in /home/abhijitnair/sandbox/newreseller/Databases.php on line 33
why this error is coming?
Properties may not be preset with runtime information.
Quoting PHP Manual:
Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. 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.
<?php
class Databases {
public static $liveresellerdb;
}
Databases::$liveresellerdb = new Database('1host1','user','pswd','db');
?>
This is how you initialise a static member...
Because you forgot to write the static keyword to actually make the property static.
In addition, you can't initialise static properties with expressions like this. Here's a workaround.
you cannot assign object during the class preperation stages, only the class instantation:
class Databases
{
public $liveresellerdb;
public function __construct()
{
$this->liveresellerdb = new Database('1host1','user','pswd','db');
}
}
anything within the constructor can be generic PHP code, outside the function and instead the class body has specific laws.
if you require the database's to be static then you have to set / access them differently.
class Databases
{
public static $liveresellerdb;
}
Databases::liversellerdb = new Database('1host1','user','pswd','db');
starting use oop
why:
class user
{
private $pdo;
function __construct()
{
$this->pdo = singleton::get_instance()->PDO_connection();
}
...
}
this works fine. but this:
class user
{
private $pdo = singleton::get_instance()->PDO_connection();
...
}
this does not working. Error parse error, expecting ','' or ';'' in ...
what is wrong with second variant?
See the last sentence of the first paragraph of Properties in the PHP OOP documentation:
Class member variables are called
"properties". You may also see them
referred to using other terms such as
"attributes" or "fields", but for the
purposes of this reference we will use
"properties". They are defined by
using one of the keywords public,
protected, or private, followed by a
normal variable declaration. 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.
In other words, the database handler returned by this statement is not a constant value and therefore will not be available at compile time:
singleton::get_instance()->PDO_connection();
Class properties cannot be assigned at declaration using functions. Scalar values, constants (though not constants of the current class), and arrays only.