add function to an array in php - php

I'm having trouble declaring an array in conjunction to a function. Here is my code, what am I doing wrong?
private function array_list(){
return array('1'=>'one', '2'=>'two');
}
private $arrays= array(
'a'=>array('type'=>'1', 'list'=>$this->array_list())
);
Getting unexpected T_VARIABLE error when I run this code.

You cannot declare arrays like this as property:
private $arrays= array(
'a'=>array('type'=>'1', 'list'=>$this->array_list())
);
You cannot use an array returned from a class method in the property definition.
You should populate it inside a constructor for example. Like this:
private $arrays = array();
public function __construct() {
$this->arrays = array(
'a'=>array('type'=>'1', 'list'=>$this->array_list())
);
}

Do it in a method, for example, the constructor:
class Foo {
function __construct () {
$this->arrays['list'] = $this->array_list ();
}
}

Related

Access an array of a class in another class without passing arguments in php

$mile= new mile();
$get_sales_totals1=mysql_query("SELECT title,deadline FROM milestones where id=$id ");
while($milestone = mysql_fetch_array($get_sales_totals1)){
$mile->addne($milestone["deadline"],$milestone["title"]);
}
I am trying to create an array of objects from database query.Above code is the main.php page and below is the page with classes.I created an array with deadline and title in each item of the array.
class mile {
public $milearray;
public function __construct(){
$this->milearray=array();
}
public function addne($deadline,$title){
$ne->deadline=$deadline;
$ne->title=$title;
array_push($this->milearray,$ne);
}
public function extra(){
//how to get milearray $this->milearray here
}
}
Is it possible to get milearray in the function 'extra' in the same class without passing arguments.
OR
class compare is incomplete. I need to call milearray from class 'mile' inside class 'compare' without passing any arguments
class compare{
public daycomparearray;
public function __construct(){
$this->daycomparearray=array();
}
public function comparemile(){
if($this->daycomparearray== milearrray->deadline)
// how to get mile array here
}
}
please help me....
You have to pass arguments, otherwise the compare class won't know which objects to compare.
class compare{
public function __construct(){
}
public function comparemile($mile1, $mile2){
$array1 = $mile1->milearray;
$array2 = $mile2->milearray;
// code that compares $array1 and $array2
}
}
If you can't pass arguments to the comparemile function, maybe it can be done with the constructor.
class compare{
private $array1;
private $array2;
public function __construct($mile1, $mile2){
$this->array1 = $mile1->milearray;
$this->array2 = $mile2->milearray;
}
public function comparemile(){
// code that compares $this->$array1 and $this->$array2
}
}
You tried self? Like:
public function extra(){
$array = self::$milearray;
}
or making a session for global vars?

Array inside function not working?

PHP CODE
class XXX{
public function ggGet($str){
return gGet($str); // This is ok working gGet is global function
}
public static $Array = array ( "value" => $this->ggGet("email")); // This code is error Why?
}
I must use a function in array in class.
I see this error.
Parse error: syntax error, unexpected '$this' (T_VARIABLE) in /var/www/html/
What must i do?
Thank you.
Try this:
class XXX{
$MyArray = array();
public function __construct(){
$this->MyArray["value"] = $this->ggGet("email");
}
public function ggGet($str){
return gGet($str);
}
}
Use __construct() every time you need to start values in a var inside a class.

How to access and modify array inside class?

I'm having problems with an array inside a class. I can access it if I set it to static but I cannot figure out how to modify it and access it on my function if it's not static.
class Example {
protected static $_arr = array(
"count",
);
public static function run($tree) {
$_arr[] = "new";
print_r($_arr );
}
}
How do I access the array, modify it and print it from inside my public function "run"?
$_arr[] = "new";
refers to an array that will be local to your function. to access a static variable of your class, you have to use the syntax ==> self::staticVariableName
you code should be :
class Example {
protected static $_arr = array(
"count",
);
public static function run($tree) {
self::$_arr[] = "new";
print_r(self::$_arr );
}
I have just made a snippet from the code of #MQuirion . Here I wrote how to handle non-static properties in your class. I hope now you can work with your array inside your class.
class Example {
protected $_arr = array(
"count",
);
public function run($tree) {
// print new array + your properties
$this -> _arr[] = $tree;
//To print only new assigned values without your declared properties
$this -> _arr = $tree;
print_r($this->_arr );
}
}
$obj = new Example();
$tree = array('a','b','c');
$result = $obj->run($tree);

php static array initialization workaround

I'm not sure what I should be searching to figure out this issue, so I'll show the code and describe the issue:
PHP Code:
<?php
class Foo
{
private static
$defaultSettings = array(
'bar' => new Baz() //error here
);
private
$settings;
public function __construct( $options = null )
{
$this->settings = isset( $options ) ? array_merge( self::$defaultSettings, $options ) : self::$defaultSettings;
}
}
class Baz
{
...code...
}
The Error:
Parse error: syntax error, unexpected T_NEW in [filename] on line [number]
What I'd like to do is have Foo::$defaultSettings contain an instance of an object, but I can't initialize the object when I create the array.
Is there a simpler way around this issue than a static initializer?
Static initializer code for Foo:
//self::init() would be called on the first line of __construct
private static function init()
{
static $initialized;
if ( !$initialized )
{
$initialized = true;
self::$defaultSettings['bar'] = new Baz();
}
}
I feel like there should be a simpler way around this issue than having to run an initializer.
Edit to add:
I could also make the initializer function public and call it immediately after the class definition as Foo::init(); which would reduce the overhead of the __construct function; however, I can't really see a single method call being significant savings.
Class properties cannot evaluate or instantiate anything, unfortunately. The closest you can do is run something from your constructor.

how can I get around no arrays as class constants in php?

I have a class with a static method. There is an array to check that a string argument passed is a member of a set. But, with the static method, I can't reference the class property in an uninstantiated class, nor can I have an array as a class constant.
I suppose I could hard code the array in the static method, but then if I need to change it, I'd have to remember to change it in two places. I'd like to avoid this.
You can create a private static function that will create the array on demand and return it:
class YourClass {
private static $values = NULL;
private static function values() {
if (self::$values === NULL) {
self::$values = array(
'value1',
'value2',
'value3',
);
}
return self::$values;
}
}
I put arrays in another file and then include the file wherever I need it.
I am having a really really hard time understanding your question. Here is essentially what I understood:
I need to maintain a proper set, where
no two elements are the same.
PHP does not have a set type, not even in SPL! We can emulate the functionality of a set but any solution I can think of is not pleasant. Here is what I think is the cleanest:
<?php
class Set {
private $elements = array();
public function hasElement($ele) {
return array_key_exists($ele, $elements);
}
public function addElement($ele) {
$this->elements[$ele] = $ele;
}
public function removeElement($ele) {
unset($this->elements[$ele]);
}
public function getElements() {
return array_values($this->elements);
}
public function countElements() {
return count($this->elements);
}
}
Example usage:
<?php
$animals = new Set;
print_r($animals->getElments());
$animals->addElement('bear');
$animals->addElement('tiger');
print_r($animals->getElements());
$animals->addElement('chair');
$animals->removeElement('chair');
var_dump($animals->hasElement('chair'));
var_dump($animals->countElements());

Categories