0

I want to create an array which is in my function.php code definded so I do not have to transfer the array through my hole code. But it won't work...

This is an example of my function.php:

<?php define("titleArray", array()); function foo(){ echo $this->titleArray; } function boo(){ array_push($this->titleArray, "Hello"); } 

But it doesn't work... How can I fix that so that every function has access to the array?

Greetings

1
  • 1
    Are you actually using classes in your real code? If so, make your title array a class property, then it's available to every method in that class Commented Feb 19, 2017 at 12:10

4 Answers 4

2

I suggest that you store your array globally using the $GLOBALS, and instead of using echo to print an array, use the print_r method instead.

<?php $GLOBALS["titleArray"] = array('world'); function foo(){ print_r($GLOBALS["titleArray"]); } function boo(){ array_push($GLOBALS["titleArray"], "Hello"); print_r($GLOBALS["titleArray"]); } foo(); boo(); 
Sign up to request clarification or add additional context in comments.

2 Comments

And if I edit the array e.g. in boo() and I call another function after that, that function is also dealing with that edited array by boo() or is it again only filled with "world"?
Yes because the array is declared globally, any changes made, would also be reflected by other methods that use the global array.
1

just remove $this

<?php define("titleArray", array()); function foo(){ echo titleArray; } function boo(){ array_push(titleArray, "Hello"); } 

note that array values are allowed after php 7.0 version

Comments

1

Generally we use define to make constant value which never updates, use class instead

 <?php class abc { $titleArray = []; function foo(){ echo $this->titleArray; } function boo(){ array_push($this->titleArray, "Hello"); } } 

The define() function defines a constant. Constants are much like variables, except for the following differences: A constant's value cannot be changed after it is set.

1 Comment

Dear readers NEVER use OOP unless you absolutely have to, and never for something so trivial
1

There are two ways to do it:

  • use global in every function
  • declare $GLOBALS[] once outside the function

$titleArray = []; // $GLOBALS['titleArray'] = []; function foo(){ global $titleArray; print_r($titleArray); // print_r($GLOBALS['titleArray']); } function boo(){ global $titleArray; array_push($this->titleArray, "Hello"); // array_push($GLOBALS['titleArray'], "Hello"); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.