Use Array From Function 1 in Function 2 - php

I have a (simplified) function that uses in_array() to check if a value is in an array:
function is($input) {
$class = array('msie','ie','ie9');
$is = FALSE;
if (in_array($input, $class)) {$is = TRUE;}
return $is;
}
if (is('msie'))
echo 'Friends don\'t let friends use IE.';
I want to break this into two separate functions, where the first defines the array:
function myarray() {
$class = array('msie','ie','ie9');
}
and the second runs the check—either like this:
function is($input) {
myarray();
$is = FALSE;
if (in_array($input, $class)) {$is = TRUE;}
return $is;
}
Or this:
function is($input) {
global $class;
$is = FALSE;
if (in_array($input, $class)) {$is = TRUE;}
return $is;
}
But both of the above cause this error:
Warning: in_array() [function.in-array]: Wrong datatype for second argument in /home/vanetten/temp.ryanve.com/PHP/airve.php on line 73
What is the proper way use an array from one function in another? Can an array be a global variable? How do I make this work? Is it more efficient to use a global variable or to call the first function within the second function. Any help is definitely appreciated.

Return the array from the first function:
function myarray() {
return array('msie','ie','ie9');
}
function is($input) {
$array = myarray();
return in_array($input, $array);
// or even just
// return in_array($input, myarray());
}

function is($input) {
$class = myarray();
$is = false;
...

Easiest way (which also negates the use of global variables, which is a bad practice since using $class somewhere else down the line may result in unexpected behavior) is something like
function myarray() {
return array('msie','ie','ie9');
}
function is($input) {
$array = myarray();
$is = FALSE;
if (in_array($input, $array)) {$is = TRUE;}
return $is;
}
if (is('msie'))
echo 'Friends don\'t let friends use IE.';
In this example, we just make myarray() return the needed array. In is(), add the line $array = myarray(), which will save the array from myarray(), so it is useable from is() as the alias $array. Then simply change $class to $array, and it should work fine.

Related

How can I get/set a property dynamically having a path without recursion?

I would like to get/set a property of a property of a property (...) having the path. For example, if I have
$obj->a->b->c
I would like to get it with
get_property(["a", "b", "c"], $obj)
I've written this function for getting it and it works for array and object values but I need it for objects.
public static function get_value_by_path($index, $array) {
if (!$index || empty($index))
return NULL;
if (is_array($index)) {
if (count($index) > 1) {
if (is_array($array) && array_key_exists($index[0], $array)) {
return static::get_value_by_path(array_slice($index, 1), $array[$index[0]]);
}
if (is_object($array)) {
return static::get_value_by_path(array_slice($index, 1), $array->{$index[0]});
}
return NULL;
}
$index = $index[0];
}
if (is_array($array) && array_key_exists($index, $array))
return $array[$index];
if (is_object($array) && property_exists($array, $index)) return $array->$index;
return NULL;
}
My question is: is it possible to do this without recursion?
I haven't found similiar questions.
This function below will do it:
function get_property($propertyPath, $object)
{
foreach ($propertyPath as $propertyName) {
// basic protection against bad path
if (!property_exists($object,$property)) return NULL;
// get the property
$property = $object->{$propertyName};
// if it is not an object it has to be the end point
if (!is_object($property)) return $property;
// if it is an object replace current object
$object = $property;
}
return $object;
}
depending on what you exactly want to can build in some error code. You can use the get function if you want to set something like this:
function set_property($propertyPath, &$object, $value)
{
// pop off the last property
$lastProperty = array_pop($propertyPath);
// get the object to which the last property should belong
$targetObject = get_property($propertyPath,$object);
// and set it to value if it is valid
if (is_object($targetObject) && property_exists($targetObject,$lastProperty)) {
$targetObject->{$lastProperty} = $value;
}
}
I do however like recursion, and with it these functions could possibly be better.

PHP T_OBJECT_OPERATOR | Variable Set

Working on a project of translating website and I had chose this solution
.
I'm trying to accomplish something like :
$VAR1 = $translate->__('Word_To_Translate');
This, not works for me since, the result is directly shown in stdout of the webpage. Even so when trying to call $VAR1 no result is returned.
This is not easily possible with the class you've mentioned.
If you wish to edit the class so it'll return the value instead of echoing it, you can edit class.translation.php, replace the two occurances of echo $str; with return $str;, and replace echo $this->lang[$this->language][$str]; with return $this->lang[$this->language][$str] (simply changing echo to return on both instances).
//$VAR1 delegating
$VAR1 = $translate->__('Word_To_Translate');
//class.translation.php
`class Translator {
private $language = 'en';
private $lang = array();
public function __construct($language){
$this->language = $language;
}
private function findString($str) {
if (array_key_exists($str, $this->lang[$this->language])) {
return $this->lang[$this->language][$str];
return;
}
return $str;
}
private function splitStrings($str) {
return explode('=',trim($str));
}
public function __($str) {
if (!array_key_exists($this->language, $this->lang)) {
if (file_exists($this->language.'.txt')) {
$strings = array_map(array($this,'splitStrings'),file($this->language.'.txt'));
foreach ($strings as $k => $v) {
$this->lang[$this->language][$v[0]] = $v[1];
}
return $this->findString($str);
}
else {
return $str;
}
}
else {
return $this->findString($str);
}
}
}`
Switched the echo for a return
Thank you very much uri2x && Rizier123.
For the moment looks that it is working solution.
Best wishes !

How to call a callback function in a PHP class

I want to use array_filter to remove those items in an array whose value is equal to a specific character like '.' . To do, so I used the following code but I don't know how to pass the callback function to array_filter:
class Myclass(){
private function isPunc($var){
if($var=='.'){
return TRUE;
}else{
return FALSE;
}
public function myfunction($arr){
$arr = array_filter($arr,"isPunc");
}
}
Any idea how to solve this problem?
class Myclass(){
private function isPunc($var) {
if ($var=='.') {
return TRUE;
} else {
return FALSE;
}
}
public function myfunction($arr) {
$arr = array_filter($arr, array($this,'isPunc'));
}
}
use $arr = array_filter($arr, array($this, 'isPunc'));
array_filter() expects a Callable. This is an special internal type in PHP that can be on of four things:
a string with function name
an array with an object and method name as elements
an anonymous function
a functor (an object that implements __invoke)
In your case the second variant should work:
class FilterIsDot {
private function accept($element) {
if($element == '.'){
return TRUE;
}else{
return FALSE;
}
}
public function filter($array) {
return array_filter(
$array, array($this, 'accept')
);
}
}
$in = array('.', 'foo');
$filter = new FilterIsDot();
var_dump($filter->filter($in));
I would suggest a different approach avoiding array_filter(). SPL contains a FilterIterator class. You can extends this class:
class FilterIsDot extends FilterIterator {
public function __construct($arrayOrIterator) {
parent::__construct(
is_array($arrayOrIterator)
? new ArrayIterator($arrayOrIterator)
: $arrayOrIterator
);
}
public function accept() {
if($this->current() == '.') {
return TRUE;
}else{
return FALSE;
}
}
}
$in = array('.', 'foo');
$filter = new FilterIsDot($in);
var_dump(iterator_to_array($filter));
In this case the filter works on the fly. It is only used if the elements are actually accessed.

Running a loop that has a function inside it

I have a problem trying to run a code inside the loop, my loop consist of a function.
Here is my coding:
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++){
$val = $new[$i];
function myfunction($value) {
//Do something
}
echo $val;
}
The problem is the code outputs only the 1st value in my array. I am very confused, am I not suppose to declare a function inside the loop?
Your code ends up with Fatal error, since at the second iteration it tries to redeclare function myfunction. That's why it is printing only first value of array.
In order to avoid that fatal error you can check if that function has been already defined using function_exists() function like this:
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++)
{
$val = $new[$i];
if(!function_exists('myfunction'))
{
function myfunction($value) {
//Do something
}
}
echo $val;
}
PHP is a scripting language and it is syntactically correct to declare a function inside for loop or inside if statement, but it is a bad practice and can cause a lot of errors afterwards.
The best way is to declare a function outside loop, and, if needed, call it from within a loop like this:
<?php
function myfunction($value) {
//Do something
}
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++)
{
$val = $new[$i];
myfunction($value); //may you was intended to pass $val here?
echo $val;
}
Don't declare the function inside the loop, declare it before the loop and then call to it inside the loop with myFunction($value);
the function should be in a separate procedure
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++)
{
$val = $new[$i];
myfunction($val)
echo $val;
}
then this is your function
function myfunction($value)
{
//Do something
}
Declare the function outside of the loop
either return a value from the function, or let the function output data
For example:
function myfunction($value) {
//Do something
echo $value;
}
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++) {
myfunction($new[$i]);
}
I am assuming you want to print out the first 4 elements of the array.
do something like this
function myfunction() {
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++){
$val = $new[$i];
echo $val;
}
}
myfunction();
You should declare the function outside the loop
function myfunction($value) {
return ($value + 25); // an example
}
$new = array(1,2,3,4);
for($i = 0; $i < count($new); $i++){
echo myfunction($new[$i]);
}
Also you should set the loop from 0 to the end of the array, so if you'll have more than 4 entries in the array the code should be ok
You can declare an anonymous function instead:
for ($i=0; $i<=3; $i++) {
// code
$myFunction = function($value) { /* code */ }
$myFunction($val);
// code
}
that is not the right way to do it...
first declare the function outside the loop, then call the function in the loop
function myfunction($value) {
//Do something
}
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++){
$val = $new[$i];
myfunction( $val); //call function where u wanted... here (in your case)
echo $val;
}
You are not suposed to declare the function inside a loop...

PHP function in a function

I am trying to build a function that will call another function.
For example, if I have an array full of function names to call, is it possible to call a function for every array value without writing it in a script?
Example:
function email($val=NULL) {
if($val)
$this->_email = $val;
else
return $this->_email;
}
function fname($val=NULL) {
if($val)
$this->_fname = $val;
else
return $this->_fname;
}
For email, fname, etc.
But I want to have it like:
function contr_val($key,$val) {
function $key($val=NULL) {
if($val)
$this->_$key = $val;
else
return $this->_$key;
}
function $key($val="hallo");
}
And call it with:
contr_val("email", "test")
You're really trying to create member variables dynamically and retrieve their values. This is what __get() and __set() are for.
Here's how you could use it:
class TestClass {
var $data = array();
public function __set($n, $v) { $this->data[$n] = $v; }
public function __get($n) {
return (isset($this->data[$n]) ? $this->data[$n] : null);
}
public function contr_val($k, $v = NULL) {
if ($v)
$this->$k = $v;
else
return $this->$k;
}
};
$sherp = new TestClass;
$sherp->contr_val("Herp", "Derp");
echo "Herp is: " . $sherp->contr_val("Herp") . "\n";
echo "Narp is: " . $sherp->contr_val("Narp") . "\n";
Something like this:
/*
Input: $val - any value
$varname - the variable name, for instance: _email
*/
function checkValue($val=NULL, $varname) {
if($val)
$this->$var = $val;
else
return $this->$var;
}
checkValue("hello", "_email");
checkValue("hello2", "_name");
If you are doing this for a class, consider using PHP's magic methods __get() and
__set().
In an array full of function names, this calls every function that exists.
ghoti#pc:~$ cat functest.php
#!/usr/local/bin/php
<?php
function one() { print "one\n"; }
function two() { print "two\n"; }
function three() { print "three\n"; }
$a=array( "one", "two", "three", "four" );
foreach ($a as $item) {
if (function_exists($item)) {
$item();
} else {
print "No such function: $item\n";
}
}
ghoti#pc:~$ ./functest.php
one
two
three
No such function: four
ghoti#pc:~$
You need to check if the function exists or not:
function contr_val($key,$val) {
if (!function_exists($key)) {
function $key($val=NULL) {
if ($val)
$this->_$key = $val;
}
}
else {
return $this->_$key;
}
}

Categories