how to declare array index as boolean in function parameter in php - php

First look at my php script:
<?php
class user{
public function check_array($option['myname']=FALSE){
if($option['myname']==False){
echo $option['yourname'];
}else{
echo $option['myname'];
}
}
$user = new user();
$option['yourname']='Mr. X';
$option['myname']='Mamun';
$user->check_array();
?>
Objective is my script is to pass argument/parameter in class method call. If the parameter is an array and if I want to declare an array element as False (by default), the how to declare it in proper way.
The above code is not working. It is showing following error:
Parse error: syntax error, unexpected '[', expecting ')' ..........
How can I declare the above array element in right way?

function check_array(array $option) {
$option += array('myname' => false, 'yourname' => null);
if ($option['myname'] !== false) {
echo $option['myname'];
} else {
echo $option['yourname'];
}
}
$option = array(
'yourname' => 'Mr. X',
'myname' => 'Mamun'
);
check_array($option);
You cannot declare the array structure and its default content as part of the function signature, it's simply not possible and arguably makes little sense. You can simply amend the array with default values programmatically inside the function with + though. You can also require the argument to be an array through type hinting, which I've done above.
I've also taken the liberty to remove anything related to class, since it's unnecessary for this example.

You can't declare default values to keys of function arguments.
You can achieve your goal in several ways, e.g.:
public function check_array($option) {
if (is_array($option) && !isset($option['myname'])) {
$option['myname'] = false;
}
// do something else
}

Related

Using custom functions dynamically in Twig?

I have the following class method for creating a Twig environment object.
public function getView($filename,
array $customFunctions = null,
array $customFunctionArgs = null,
$debug = false) {
$loader = new \Twig_Loader_Filesystem('/App/Views/Templates/Main');
$twig = new \Twig_Environment($loader);
if (isset($customFunctions)) {
foreach ($customFunctions as $customFunction) {
$customFunction['name'] = new \Twig_SimpleFunction($customFunction['name'],
function ($customFunctionArgs) {
return $customFunction['method']($customFunctionArgs);
});
$twig->addFunction($customFunction['name']);
}
}
// Check debugging option
if ($debug == true && !$twig->isDebug()) {
$twig->enableDebug();
$twig->addExtension(new \Twig_Extension_Debug());
} elseif (!$debug && $twig->isDebug()) {
$twig->disableDebug();
}
$template = $twig->load($filename);
return $template;
}
Problem is, I don't understand how to pass values in order to make this work dynamically and keep all the objects in context and scope. For instance, here is how I'm trying to use it but can't pass the variables as a reference I guess?
$customFunctions = ['name' => 'customFunctionName',
'method' => $Class->method($arg)];
$customFunctionArgs = [$arg];
$template = $View->getView('template.html.twig', $customFunctions, $customFunctionArgs, true);
My environment is PHP 5.6 & Twig 1.35.0. I suppose this is not a Twig specific question per se, but more of how to use class objects within other classes/methods.
FĂ©lix Gagnon-Grenier's answer helped me find a solution to this problem. However, I feel the need to post an answer with all the missing pieces to the puzzle for anyone that needs a solution for this.
I believe it will make more sense if I start at the end and explain to the beginning. When creating your array, there are several things to consider.
Any class objects that are needed for the function have to be declared inside a use() with the closure.
Any arguments for the custom function must be declared as a function parameter for the closure. This will allow you to declare them later.
I ended up adding a sub-array with the arguments I needed for each custom function, that way I don't need to iterate over them separately.
$customFunctions = [
[
'name' => 'customFunction',
'method' => function($arg1, $arg2) use($Class) {
return $Class->customFunction($arg1, $arg2);
},
'arguments' =>
[
'arg1', 'arg2'
]
]
];
$template = $View->getView(
'template.html.twig',
true,
$customFunctions
);
echo $View->renderView($template);
Based on this code (reflective of question above), I had to make some notable modifications.
if (isset($customFunctions)) {
foreach ($customFunctions as $index => $customFunction) {
if (isset($customFunctions['arguments'])) {
$arguments = $customFunctions['arguments'];
} else {
$arguments = [];
}
$twigFunction = new \Twig_SimpleFunction(
$customFunction['name'],
function (...$arguments) use ($customFunction) {
return $customFunction['method'](...$arguments);
});
$twig->addFunction($twigFunction);
}
}
You can do this whatever way works for you, but there are important things to consider which I struggled with. Once again, your arguments MUST go into the function parameters. function (...$arguments) use ($customFunction). Your custom function will be passed in the use(). In order to actually pass the arguments in the closure, you must use ... to unpack them (as an array). This applies to PHP 5.6+. It allows the arguments to be dynamically expanded to the correct amount, otherwise you will get missing argument errors.
There are slight flaws in how you construct the custom functions data array and the loop that injects them into the template.
The custom functions should be a three dimensional array
$customFunctions = [
[ // notice the extra level, allowing you to access the name
'name' => 'customFunctionName',
'method' => function() { return 'wat'; }
// you need to pass a callable, not the result of a call
]
];
The scope is not inherited like you seem to think it is, you need to use() variables you intend to access. I personnally would not overwrite the 'name' value of the array, but that's uncanny paranoia of internal side effects, it seems to work in practice.
if (isset($customFunctions)) {
foreach ($customFunctions as $customFunction) {
$customFunction['name'] = new \Twig_SimpleFunction(
$customFunction['name'],
function () use ($customFunctionArgs, $customFunction) {
return $customFunction['method']($customFunctionArgs);
});
$twig->addFunction($customFunction['name']);
}
}
You might need to add looping over $args so that the correct args are sent to the correct function (send $args[0] to $customFunctions[0] etc.).
Note that this prevents you from sending a parameter into your custom function unless you add it in the loop:
function ($templateArg) use ($customFunctionArgs, $customFunction) {
return $customFunction['method']($customFunctionArgs, $templateArg);
}
Here is a gist with tests if you're interested.

Passing an array as the parameter of a function in PHP

This is my array
$sub = array("English"=>"12","Hindi"=>"12","History"=>"12","Geography"=>"12","Mathematics"=>"12","Physics"=>"12","Chemistry"=>"12","Biology"=>"12");
Want to pass this entire array as the parameter of a function & want to sum up the marks(array values) using the function
function sum_marks($sub){--Function body--
}
I don't know if this is the proper syntax for passing an array to a function, help!!
Is this you are looking for?
$mySum = array_sum($sub);
Yes, it is the appropriate syntax for passing an array as an argument to a function.
However, you might consider adding a type declaration for the $sub argument:
function sum_marks(array $sub)
{
return array_sum($sub);
}
Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.
However, you really probably just want to use array_sum() directly.
For reference, see:
http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration
http://php.net/manual/en/function.array-sum.php
Try this. It will create a function that has a reference to your array. When you change the array you can call the product of the function, and it will recalculate the sum.
$array = ['English' => '12', 'Swedish' => '12'];
function arraySumCb(&$subject) {
return function () use (&$subject) {
return array_sum($subject);
};
}
$sum = arraySumCb($array);
echo $sum(); // 24
$array['Swedish'] = '15';
echo $sum(); // 27
$array['Swedish'] = '10';
echo $sum(); // 22
Edit: This is how I would do it.
$array = ['English' => '12', 'Swedish' => '12'];
class SumMarks {
private $_subject;
public function __construct(array &$subject = []) {
$this->_subject = &$subject;
}
public function __toString() {
return "" . array_sum($this->_subject);
}
}
$sum = new SumMarks($array);
echo $sum; // 24
$array['Swedish'] = '10';
echo $sum; // 22
Edit: Proper use of PHP anonymous functions
I dont understand your question, please ask with specific question. .
But maybe this what are you want :
function sum_marks($sub){
$result = array_sum($sub);
retrun $result;
}

what does it mean by array $options = [] in method argument

I found a php class in the internet that uses array $options = [] in method argument:
class TADFactory
{
private $options;
public function __construct(array $options = [])
{
$this->options = $options;
}
//some other methods here
}
and in page.php file
$tad_factory = new TADFactory(['ip'=>'192.168.0.1']);
//some other stuffs here
But after executing the page.php file in the browser, it is showing:
Unexpected `[` in page.php file at line 1, expecting `)`....
But according to the php library documentation, I have to use the multidimensional array in argument by that way.
I could not understand what does it mean by array $options = [] in TADFactory class argument and why the error is throwing?
That is a default argument value. It is how you declare that a parameter is optional, and, if not provided, what value it should have by default.
function add($x, $y = 5) {
return $x + $y;
}
echo add(5, 10); // 15
echo add(7); // 12
As for the array annotation, that is a type hint (also called a type declaration), which means that you must pass the function an array or it will throw an error. Type hinting is fairly complicated and debatably necessary in a dynamic language, but it's probably worth knowing about.
function sum(array $nums) {
return array_sum($nums);
}
echo sum([1, 2, 3]); // 6
echo sum(5); // throws an error
NOTE: You can only combine type hints with default argument values if your default argument value is null.

PHP or operator similar to javascript? Is there a simple way?

In javascript I can pass an object literal to an object as a parameter and if a value does not exist I can refer to a default value by coding the following;
this.title = params.title || false;
Is there a similar way to do this with PHP?
I am new to PHP and I can't seem to find an answer and if there is not an easy solution like javascript has, it seems pure crazy to me!!
Is the best way in PHP to use a ternary operator with a function call?
isset($params['title']) ? $params['title'] : false;
Thanks
Don't look for an exact equivalent, because PHP's boolean operators and array access mechanism are just too different to provide that. What you want is to provide default values for an argument:
function foo(array $params) {
$params += array('title' => false, ...);
echo $params['title'];
}
somethig like this $title = (isset($title) && $title !== '') ? $title : false;
Or using the empty function:
empty($params['title']) ? false : $params['title'];
$x = ($myvalue == 99) ? "x is 99": "x is not 99";
PHP one liner if ...
if ($myvalue == 99) {x is 99} else {x is not 99 //set value to false here}
<?php
class MyObject {
// Default value of object property
public $_title = null;
// Default value of argument (constructor)
public function __construct($title = null){
$this->_title = $title;
}
// Default value of argument (setter)
public function setTitle($title = null){
// Always validate arguments if you're serious about what you're doing
if(!is_null($title) and !is_string($title)){
trigger_error('$title should be a null or a string.', E_USER_WARNING);
return false;
}
$this->_title = $title;
return true;
}
} // class MyObject;
?>
This is how you do an object with default values. 3 ways in 1. You either default the property value in the class definition. Or you default it on the __construct assignment or in a specific setter setTitle.
But it all depends on the rest of your code. You need to forget JS in order to properly use PHP. This is a slightly stricter programming environment, even if very loose-typed. We have real classes in PHP, not imaginary function classes elephants that offer no IDE code-completion support like in JS.

Accessing object properties of type array dynamically

I am building a Language class for internationalization, and I would like to access the properties dynamically (giving the string name), but I don't know how to do it when dealing with arrays (this is just an example):
class Language {
public static $languages_cache = array();
public $index_header_title;
public $index = array(
"header" => array(
"title" => NULL
)
);
}
Now I add languages like this:
Language::$languages_cache["en"] = new Language();
Language::$languages_cache["en"]->index_header_title = "Welcome!"; //setting variable
Language::$languages_cache["en"]->index["header"]["title"] = "Welcome!"; //setting array
Function for accessing members dynamically:
function _($member, $lang)
{
if (!property_exists('Language', $member))
return "";
return Language::$languages_cache[$lang]->$member;
}
So, outputting members:
echo _('index_header_title', "en"); //works
echo _('index["header"]["title"]', "en"); //does not work
I would need a way for accessing arrays dynamically.. for public and private via __set() function.
Thank you!
You could try using a separator flag so that you can parse the array path. The only problem is you are mixing you properties and arrays so that might complicate things.
You would call your function like this:
echo _('index.header.title', "en");
And your function would parse the path and return the correct value. Take a look at the array helper in Kohana 3.0. It has the exact function that you want. http://kohanaframework.org/guide/api/Arr#path

Categories