How can I define an array constant? - php

When I try to define an array as constant there is a warning! The constant must be a scalar value. But how I can define an array that I cann't modify next in my script? Any solutions?

In PHP you can not do this, so you can use some tricks:
One of the way is using serialize(also you can use implode/explode, json_encode/json_decode):
define ("MyArray", serialize (array ("first", "second", "third")));
And after that :
$MyArray = unserialize (MyArray); //here your array again
Another way is use class, in which you will have private static variable
class arrayConstant{
private static $myArray=array ("first", "second", "third"); //here you set your array
public static function getmyArray() {
return self::$myArray; //return array
}
}
$arrayConstant = arrayConstant::getArray(); //getting the array

Related

get object values as array in php

I have object with setter and getter
class obj{
private $a;
private $b;
}
I would like to create an array that get only the value of the object , for example
array = ["1","2"]
tried get_object_vars but its an associative array
To condense an associative array to an indexed array, use array_values:
array_values(get_object_vars($object));
However, given that you have private member variables, you might just want to use an array cast instead of get_object_vars:
array_values((array)$object);
See it online at 3v4l.org.

PHP: How to get single value from array that was returned from a class?

class Test {
public function results() {
$return['first'] = 'one';
$return['second'] = 'two';
return $return;
}
}
$test = new Test;
print_r($test->results()); // Returns entire array
I just want to return a single specified element from the array, such as the value of key "second". How do I do this without sifting through the entire array after it's returned?
I just want to return a single specified element from the array, such as the value of key "second"
Pass in an argument to identify which element to return, and return that (or false if it doesn't exist - for example);
public function results($key = null)
{
$return['first'] = 'one';
$return['second'] = 'two';
// check the key exists
if (!array_key_exists($key, $return)) {
return false;
}
return $return[$key];
}
Then:
print_r($test->results('second')); // two
How do I do this without sifting through the entire array after it's returned?
It's important to note that you do not need to "sift through the entire array" to retrieve a value by its key. You know the key, so you can access it directly.
class Test {
private $arr; //private property of object
__construct(){
//create arr in constructor
$this->arr=[];//create new array
$this->arr['first'] = 'one';
$this->arr['second'] = 'two';
}
/**
/* get array
**/
public function getResults(){
return $this->arr;
}
/**
/* get single array element
**/
public function getResult($key) {
return isset($this->arr[$key])?$this->arr[$key]:null;//return element on $key or null if no result
}
}
$test = new Test();
print_r($test->getResult("second")); // Returns array element
//or second possibility but the same result
print_r($test->getResults()["second"]); // Returns array element
Few advices:
Create data structure in constructor ($arr in this particular case) because creating it on very results method call is not any kind of using objects or objective programming. Imagine that if array is created in results method then on every call new array is located in memory, this is not efficent, not optimal and gives no possibility to modify this array inside class Test.
Next in method results add parameter to get only this key what is needed and hide all array in private class property $arr to encapsulate it in object.
And last my private opinion for naming style:
Use camelCase when naming method names.
In PHP an array value can be dereferenced from the array by its key.
$arr = ["foo" => "bar", "baz" => "quix"];
echo $arr["foo"]; // gives us "bar"
echo $arr["baz"]; // gives us "quix"
If the method/function returns an array the same can be done with the return value, whether by assigning the return value to a variable and using the variable to dereference the value by key, or by using function array dereferencing.
class Test {
public function results() {
return ["foo" => "bar", "baz" => "quix"];
}
}
$test = new Test;
$arr = $test->results();
echo $arr["foo"]; // gives us "bar"
echo $arr["baz"]; // gives us "quix"
// Using FAD (Function Array Dereferencing)
echo $test->results()["foo"]; // gives us "bar"
echo $test->results()["baz"]; // gives us "quix"
Of course there are two important caveats to using function array dereferencing.
The function is executed each time you do it (i.e no memoziation)
If the key does not exist or the function returns something other than array, you get an error
Which means it's usually safer to rely on assigning the return value to a variable first and then doing your validation there for safety... Unless you are sure the function will always return an array with that key and you know you won't need to reuse the array.
In PHP 5.4 and above:
print_r($test->results()['second']);
In older versions which you shouldn't be running as they are out of security maintenance:
$results = $test->results();
print_r($results['second']);
Edit: The first example originally said 5.6 and above but array dereferencing was introduced in 5.4! For the avoidance of doubt, 5.6 is the lowest php version within security maintenance.

How to specify callback function when filtering array with object elements in php?

I have an array whose items are of a certain object type, let it be my_object.
The class defining the my_objects has a function that I want to use to filter the array. How can I specify that function when calling array_filter?
class my_class{
private $exclude;
public filter_function(){
return !$this->exclude;
}
}
$array=array($my_object1, $my_object2, ....);
$filtered=array_filter($array,'filter_function');//obviously does not work
my_object1 , my_object2 , ... are all instances of my_class and I want that the
$my_object1->filter_function()
$my_object2->filter_function()
,.....
be called for filtering the array.
If you want to filter the array based on return value of each individual object's filter_function method call, you could simply:
array_filter($array, function($obj) { return $obj->filter_function(); });
No need to clutter the original class with static methods as in Mark's answer.
You need to indicate the object as well as the method in your callback, using an array syntax as shown in the php docs for callbacks
class my_class{
private $exclude;
public filter_function(){
return !$this->exclude;
}
}
$array = array($my_object1, $my_object2, ....);
$classFilter = new my_class();
$filtered = array_filter($array,[$classFilter, 'filter_function']);
In this case, you need to create an instance first, then use that instantiated object as the first element in the callback, and the method name as the second element
EDIT
However, if you're trying to filter this collection of my_class objects based on whether individual objects have the exclude set, then you need to have a filter method for the collection:
class my_class{
private $exclude;
public filter_function(){
return !$this->exclude;
}
public static filter_collection($value){
return $value->filter_function();
}
}
$array = array($my_object1, $my_object2, ....);
$filtered = array_filter($array,['my_class', 'filter_collection']);

Convert array into object

I have a own Array class. Like this:
myArray::fetch('site.meta.keywords'); // return Array(...)
At the same time, How can I do like this?
myArray::fetch('site.meta.keywords'); // return Array(...)
myArray::fetch('site.meta.keywords')->as_object(); // return Object{...}
Is it possible in PHP?
You can't because an array doesn't have an as_object method. I would make a separate fetchAsObject method in your array class, or introduce an optional asObject parameter (boolean, default false) to your existing fetch method.
You should take a look at ArrayObject, it behaves the same as any other array and you can extend it (or your class?).
In your case I'd return something like MyArrayObject (your class extending ArrayObject with method as_object() etc.).
If in first case you are returning raw PHP Array it is not possible.
You can do that way:
public static function fetch($key, $as_object = false)
{
//in $data you have your array
return ($as_object) ? (object)$data : $data;
}
myArray::fetch('site.meta.keywords'); //return array
myArray::fetch('site.meta.keywords', true); //return object
Or just simply like that:
$dataAsArray = myArray::fetch('site.meta.keywords');
$dataAsObject = (object)myArray::fetch('site.meta.keywords');

What's the technical reason why class constants can't be arrays in PHP?

Anybody knows the technical reason why this constraint is placed on PHP classes (at least in v5.1x)?
Arrays are variable - you can modify them. You can use a static property instead.
Constants cannot contain mutable types. A constant is a "variable" that cannot be changed; it cannot be assigned to, but if its value were mutable, then it could be changed just by mutating the value:
class SomeClass
{
public const $array = array(0 => 'foo', 1 => 'bar');
public static function someFunction()
{
self::$array[0] = 'baz'; // SomeClass::$array has now changed.
}
}
Don't exactly know why, but you can initialize static array variable:
class myClass {
public static $arr = Array ('foo', 'bar');
}
Note that arrays are variables, so you can modify them outside...

Categories