php function with optional parameters using stdClass - php

Suppose, I have a function such as: [$data is a stdClass()]
function test_1{
...
...
if (somecondition){
$data->name = NULL;
test_2($data->name);
}
else{
$data->name = 'hello';
test_2($data->name);
}
...
...
}
function test_2($data){
if (!empty($data->name)){
test_3($data->name);
}
else{
test_3();
}
}
function test_3($s = ''){
if (!empty($s)){
//do something
}
else{
$s .= 'World';
}
}
test_3 is the function with optional parameters.
However, I get an error: Object of class stdClass could not be converted to string

I'm assuming you called your function in a manner of the form:
$data = new stdClass();
test_3($data);
This fails then as you end up in your else statement, and you can't concatenate a stdClass() to a string (in this case 'World').
A bit more review suggests that your actual function call is test_3($data->name), and $data->name is likely of stdClass() instead of a string that can be concatenated with 'World'.
For reference, if you have an error, it'd be helpful to provide the actual line number the error is corresponding to . . . I'm guessing the error is due to the concat, since that's the only place where I see a stdClass() to string conversion would be necessary.

Related

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;
}

Getting the return value from a function

Say I got some function that run some code and then return something, like this:
function something()
{
//some code
return $some[$whatever];
}
So, if I want to extract the data I generated in the function - the new value for $some, how should I do it? for example this won't do anything:
echo ($some);
Or what am I missing here, please
Since your Function returns a value, You may need to catch & store it inside a variable and then echo the variable if it is a String or do some casting to that effect. Here's an example:
<?php
function something(){
//some code
$whatever = 3;
$some = ["Peace", "Amongst", "All", "Humanity"];
return $some[$whatever];
}
$var = something();
var_dump($var); //<== DUMPS :: "Humanity"
echo $var; //<== ECHOES:: "Humanity"
Test it out here.
Cheers and Good Luck....
You are trying to return a specif key from your array, which wasn't declared. I declared an array for you, and I added the isset to check if the key is existing in the array to prevent any php warnings.
function something($findKey)
{
$some = array('key'=> 123);
if(!isset($some[$findKey])) {
return false;
}
//some code
return $some[$findKey];
}
echo something('key');

how to declare array index as boolean in function parameter in 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
}

What does & before the function name signify?

What does the & before the function name signify?
Does that mean that the $result is returned by reference rather than by value?
If yes then is it correct? As I remember you cannot return a reference to a local variable as it vanishes once the function exits.
function &query($sql) {
// ...
$result = mysql_query($sql);
return $result;
}
Also where does such a syntax get used in practice ?
Does that mean that the $result is returned by reference rather than by value?
Yes.
Also where does such a syntax get used in practice ?
This is more prevalent in PHP 4 scripts where objects were passed around by value by default.
To answer the second part of your question, here a place there I had to use it: Magic getters!
class FooBar {
private $properties = array();
public function &__get($name) {
return $this->properties[$name];
}
public function __set($name, $value) {
$this->properties[$name] = $value;
}
}
If I hadn't used & there, this wouldn't be possible:
$foobar = new FooBar;
$foobar->subArray = array();
$foobar->subArray['FooBar'] = 'Hallo World!';
Instead PHP would thrown an error saying something like 'cannot indirectly modify overloaded property'.
Okay, this is probably only a hack to get round some maldesign in PHP, but it's still useful.
But honestly, I can't think right now of another example. But I bet there are some rare use cases...
Does that mean that the $result is returned by reference rather than by value?
No. The difference is that it can be returned by reference. For instance:
<?php
function &a(&$c) {
return $c;
}
$c = 1;
$d = a($c);
$d++;
echo $c; //echoes 1, not 2!
To return by reference you'd have to do:
<?php
function &a(&$c) {
return $c;
}
$c = 1;
$d = &a($c);
$d++;
echo $c; //echoes 2
Also where does such a syntax get used in practice ?
In practice, you use whenever you want the caller of your function to manipulate data that is owned by the callee without telling him. This is rarely used because it's a violation of encapsulation – you could set the returned reference to any value you want; the callee won't be able to validate it.
nikic gives a great example of when this is used in practice.
<?php
// You may have wondered how a PHP function defined as below behaves:
function &config_byref()
{
static $var = "hello";
return $var;
}
// the value we get is "hello"
$byref_initial = config_byref();
// let's change the value
$byref_initial = "world";
// Let's get the value again and see
echo "Byref, new value: " . config_byref() . "\n"; // We still get "hello"
// However, let’s make a small change:
// We’ve added an ampersand to the function call as well. In this case, the function returns "world", which is the new value.
// the value we get is "hello"
$byref_initial = &config_byref();
// let's change the value
$byref_initial = "world";
// Let's get the value again and see
echo "Byref, new value: " . config_byref() . "\n"; // We now get "world"
// If you define the function without the ampersand, like follows:
// function config_byref()
// {
// static $var = "hello";
// return $var;
// }
// Then both the test cases that we had previously would return "hello", regardless of whether you put ampersand in the function call or not.

objects and strings

I was trying to return a set of objects.
But this code gives me the following error:
Catchable fatal error: Object of class User could not be converted to string in ...
public function fetchObject($psClassname ="",$paParams =array()){
$lrResource = $this->mrQueryResource;
$liResult = null;
while($row = mysql_fetch_object($lrResource,$psClassname,$paParams)){
$liResult .= $row; <-this line produces the error
}
return $liResult;
}
In your code $row is a an object (you've used mysql_fetch_object), and the .= operator tries to build a string, concatenating $liResult and $row. I believe this behaviour only works if your object implements a toString method
You could return an array of rows using this code:
public function fetchObject($psClassname ="",$paParams =array()){
$lrResource = $this->mrQueryResource;
$liResult = array();
while($row = mysql_fetch_object($lrResource,$psClassname,$paParams)){
$liResult[] = $row;
}
return $liResult;
}
That's because you are trying to convert $row to a string (the .= assumes a string is given on the right hand side)

Categories