Reputation: 1205
I have a static class Tools
, where I defined a method getMsg()
to retrieve a variable : array with keys and values:
private $Msg = array()
public static function getMsg()
{
return $this->Msg;
}
Then I use this variable as follows in another class :
Tools::getMsg()['key'] = $this->message;
My question, I want to get the value by providing the key. I know about the php function
array_search — Searches the array for a given value and returns the first corresponding key if successful
But is there a function to search the array for a given key ? I don't know if the syntax of my code above is correct so, if not I may need to use a function.
Here is an example of the Msg array :
$Msg = array('Class1' => 'File does not exist',
'Class2' => 'Error in timestamp format')
Upvotes: 0
Views: 56
Reputation: 169
<?php
class Tools
{
private static $Msg = [];
public static function getMsg($key)
{
return self::$Msg[$key]
}
}
$message = Tools::getMsg('test'); // returns Tools::$Msg['test']
I don't think there is a "static class" in PHP. Not sure about other languages though. use self::
to access static properties/methods in the same class
Upvotes: 1
Reputation: 11050
To access an array, you do not need to use a built-in function. Simply access the array as follows.
$arr = array('foo' => 42, 'bar' => 'rab', 'baz' => false); // example array
echo $arr['bar']; // will output 'rab'
$key = 'foo';
echo $arr[$key]; // will output 42
As a sidenote: you cannot use $this
in a static context. Use self::$Msg
and declare $Msg
as private static $Msg
, or make the access not static at all. Your code could be along the following lines.
private static $Msg = array();
public static function getMsg()
{
return self::$Msg;
}
Upvotes: 1