Is static array property not possible in php? - php

Below is my code in php,and I am getting error:
Parse error: syntax error, unexpected '[' in /LR_StaticSettings.php on line 4
<?php
class StaticSettings{
function setkey ($key, $value) {
self::arrErr[$key] = $value; // error in this line
}
}
?>
I want to use statically not $this->arrErr[$key] so that I can get and set static properties without creating instance/object.
Why is this error? Can't we create static array?
If there is another way, please tell me. Thanks

You'd need to declare the variable as a static member variable, and prefix its name with a dollar sign when you reference it:
class StaticSettings{
private static $arrErr = array();
function setkey($key,$value){
self::$arrErr[$key] = $value;
}
}
You'd instantiate it like this:
$o = new StaticSettings;
$o->setKey( "foo", "bar");
print_r( StaticSettings::$arrErr); // Changed private to public to get this to work
You can see it working in this demo.

Your code doesn't define $arrErr as a static member variable. You should declare it as
<?php
class StaticSettings{
public static $arrErr = array();
function setkey($key,$value){
self::arrErr[$key] = $value;
}
}
?>

Related

PHP add items to catalog using array_push function in a class

how can I add items from "a.php" to an array in "catalogus.php" using array_push?
This is "a.php"
<?php
include("Catalogus.php");
$product1 = new Product();
$product1->setNaam("Muis");
$catalogus = new Catalogus();
$value = $product1;
voegProductToe($value);
?>
this is "catalogus.php"
<?php
class Catalogus{
var $producten;
$producten = array();
function voegProductToe($value){
array_push( $this->producten, "$value");
}
}
?>
I got an error when trying to run this
Parse error: syntax error, unexpected '$producten' (T_VARIABLE), expecting `function (T_FUNCTION) or const (T_CONST) in C:\xampp\htdocs\Catalogus.php on line 11
There are many issues in your php class. For starter, var ins't needed in PHP. You could make your array public or have a public function that pushes in the array. Also welcome to SO.
class Catalogus{
public $producten = [];
/*OR*/
public function addToCatalog($__item){
$this->producten[] = $__item;
}
}
$catalogus = new Catalogus();
$catalogus->producten[] = $value;
/*OR*/
$catalogus->addToCatalog($value);
The line $producten = array(); doesn't belong. If you're trying to define the property $producten as an empty array, use the assignment operator on the same line.
class Catalogus{
var $producten = array();
I'd highly recommend using the visibility keywords like private, protected or public instead of var for property definitions. http://php.net/manual/en/language.oop5.properties.php

How do I use a private php class member variable as a key in an array?

I am trying to access a private member variable to use as a key in an array.
My class looks similar to this:
<?php
class MyClassName {
private $value;
private function MyFunction($array){
$some_html = "<b> $array[$this->value] <b>"; // error occurring on this line
return some_html;
}
}
?>
The error that I am getting is
PHP Parse error: syntax error, unexpected '-', expecting ']
If I store the private member variable before using it in the array there is no syntax error. This is interpreted fine:
<?php
class MyClassName {
private $value;
private function MyFunction($array){
$cache_key = $this->value;
$some_html = "<b> $array[$cache_key] <b>";
return $some_html;
}
}
?>
Is there something I am missing? I want to improve my understanding of what is happening here. Thanks.
Try this:
$some_html = "<b> ".$array[$this->value]." </b>";

PHP Syntax Error in the Instance Declaration

i have a little syntax error which i'm not able to sort out, can anyone help ?
Syntax:
Config Class:
Error:
Do not instantiate private variables like that, you should only be using them for declaring properties and simple values.
You cannot declare a private variable (declaring them a return value from a static functions at least) like that, just do it in the constructor __construct() for the object. You will get the same error for any class you do with a private variable declaration like that and setting it as a return value for any function. Try running the below in PHPFiddle and you'll get the same error.
<?php
class A {
private $hi = B::some_function('hi');
}
class B {
public static function some_function(string) {
return $string;
}
}
?>
Instead do something like:
<?php
class A {
private $hi;
public function __construct() {
$this->hi = B::some_function('hi');
}
}
class B {
public static function some_function(string) {
return $string;
}
}
?>
Your syntax is incorrect as I've seen in that picture, simply because you didn't have a closing bracket '}' for the class User.
Just try this one.
Use semicolon for every function call as shown below,
$_table = Config::get('tables/users');
$_seassionsTable = Config::get('tables/user_sessions');
It may be fix your issue.

PHP Fatal error: Cannot access empty property

I'm new to php and I have executed below code.
<?php
class my_class{
var $my_value = array();
function my_class ($value){
$this->my_value[] = $value;
}
function set_value ($value){
// Error occurred from here as Undefined variable: my_value
$this->$my_value = $value;
}
}
$a = new my_class ('a');
$a->my_value[] = 'b';
$a->set_value ('c');
$a->my_class('d');
foreach ($a->my_value as &$value) {
echo $value;
}
?>
I got below errors. What could be the error?
Notice: Undefined variable: my_value in C:\xampp\htdocs\MyTestPages\f.php on line 15
Fatal error: Cannot access empty property in C:\xampp\htdocs\MyTestPages\f.php on line 15
You access the property in the wrong way. With the $this->$my_value = .. syntax, you set the property with the name of the value in $my_value. What you want is $this->my_value = ..
$var = "my_value";
$this->$var = "test";
is the same as
$this->my_value = "test";
To fix a few things from your example, the code below is a better aproach
class my_class {
public $my_value = array();
function __construct ($value) {
$this->my_value[] = $value;
}
function set_value ($value) {
if (!is_array($value)) {
throw new Exception("Illegal argument");
}
$this->my_value = $value;
}
function add_value($value) {
$this->my_value = $value;
}
}
$a = new my_class ('a');
$a->my_value[] = 'b';
$a->add_value('c');
$a->set_value(array('d'));
This ensures, that my_value won't change it's type to string or something else when you call set_value. But you can still set the value of my_value direct, because it's public. The final step is, to make my_value private and only access my_value over getter/setter methods
First, don't declare variables using var, but
public $my_value;
Then you can access it using
$this->my_value;
and not
$this->$my_value;
To access a variable in a class, you must use $this->myVar instead of $this->$myvar.
And, you should use access identifier to declare a variable instead of var.
Please read the doc here.
As I see in your code, it seems you are following an old documentation/tutorial about OOP in PHP based on PHP4 (OOP wasn't supported but adapted somehow to be used in a simple ways), since PHP5 an official support was added and the notation has been changed from what it was.
Please see this code review here:
<?php
class my_class{
public $my_value = array();
function __construct( $value ) { // the constructor name is __construct instead of the class name
$this->my_value[] = $value;
}
function set_value ($value){
// Error occurred from here as Undefined variable: my_value
$this->my_value = $value; // remove the $ sign
}
}
$a = new my_class ('a');
$a->my_value[] = 'b';
$a->set_value ('c'); // your array variable here will be replaced by a simple string
// $a->my_class('d'); // you can call this if you mean calling the contructor
// at this stage you can't loop on the variable since it have been replaced by a simple string ('c')
foreach ($a->my_value as &$value) { // look for foreach samples to know how to use it well
echo $value;
}
?>
I hope it helps
Interesting:
You declared an array var $my_value = array();
Pushed value into it $a->my_value[] = 'b';
Assigned a string to variable. (so it is no more array) $a->set_value ('c');
Tried to push a value into array, that does not exist anymore. (it's string) $a->my_class('d');
And your foreach wont work anymore.
This way you can create a new object with a custom property name.
$my_property = 'foo';
$value = 'bar';
$a = (object) array($my_property => $value);
Now you can reach it like:
echo $a->foo; //returns bar
I realise this answer is not a direct response to the problem described by the OP, but I found this question as a result of searching for the same error message. I thought it worth posting my experience here just in case anybody is muddling over the same thing...
You can encounter the error in question as a result of a poorly formatted for loop over an associative array. In a fit of bone-headedness, I was using -> instead of => in my for statement:
foreach ($object->someArray as $key->$val) {
// do something
}
Of course, I should have had:
foreach ($object->someArray as $key=>$val) {
// do something
}
I confused myself at first, thinking the reported error was referring to the someArray property!

How do I access static member of a class?

I am trying to access static member of a class.
my class is:
class A
{
public static $strName = 'A is my name'
public function xyz()
{
..
}
..
}
//Since I have bunch of classes stored in an array
$x = array('A');
echo $x::$strName;
I am getting error while printing. How can I print 'A is my name'
If A is a class, you can access it directly via A::$strName.
class A {
public static $strName = 'A is my name';
}
echo A::$strName; // outputs "A is my name"
Update:
Depending on what you have inside your array, whether its what I like to define as class objects or class literals could be a factor. I distinguish these two terms by,
$objClasses = array(new A(), new B()); // class objects
$myClasses = array('A','B'); // class literals
If you go the class literals approach, then using a foreach loop with PHP5.2.8 I am given a syntax error when using the scope resolution operator.
foreach ($myClasses as $class) {
echo $class::$strName;
//syntax error, unexpected '::', expecting ',' or ';'
}
So then I thought about using the class objects approach, but the only way I could actually output the static variable was with an instance of an object and using the self keyword like so,
class A {
public static $strName = 'A is my name';
function getStatic() {
return self::$strName;
}
}
class B {
public static $strName = 'B is my name';
function getStatic() {
return self::$strName;
}
}
And then invoke that method when iterating,
foreach($objClasses as $obj) {
echo $obj->getStatic();
}
Which at that point why declare the variable static at all? It defeats the whole idea of accessing a variable without the need to instantiate an object.
In short, once we have more information as to what you would like to do, we can then go on and provide better answers.
If you want a working version for PHP5.2, you can use reflection to access the static property of a class.
class A {
static $strName= '123';
}
$lstClass = array('A');
foreach ($lstClass as $value) {
$c = new ReflectionClass($value);
echo $c->getStaticPropertyValue('strName');
}
Demo : http://ideone.com/HFJCW
You have a syntax error with missing semicolon and because it is an array you need to access the index of 0, or else it would be trying to call class 'Array'.
class A
{
public static $strName = 'A is my name';
public function xyz()
{
// left blank and removed syntax error
}
}
$x = array('A');
echo $x[0]::$strName;
Should fix it.
UPDATE
If you want to iterate over an array to call a class variable:
$x = array('A', 'B');
foreach ($x as $class) {
echo $class::$strName;
}
Not sure why you would want that, but there you go. And this has been tested, no errors were thrown, valid response of A is my name was received.
EDIT
Apparently this only works under PHP 5.3
I do find next one simple solution but don't know whether its good one or not.
My soln is:
eval('return '.$x[0].'::$strName;');
From inside a class and want to access a static data member of its own you can also use
static::
instead of
self::

Categories