Default var value php

PHP how set default value to a variable in the class?

you have two options to set the default values for the class attributes:,Option 1: set at the parameter level.,Then you can use these default values in your other functions.,Why don’t we get first and how set right default value variable $name only for class A?

You can use a constructor to set the initial values (or pretty much do anything for that matter) as you need to like this:

Then you can use these default values in your other functions.

class example < public $name; public function __construct() < $this->name="first"; > public function test1($inputName) < if(!empty($inputName)) < $this->name=$inputName; > echo "The name is ".$this->name."\r\n"; > > $ex=new example(); $ex->test1(" "); // prints first. $ex->test1("Bobby"); // prints Bobby $ex->test1($_POST["name"]); // works as you expected it to. 

Answer by Brodie Velazquez

In php, How do I set default values to properties that where not specified during the instance creation?,If you wanted to set values after the product creation you can also use a setter method instead of passing default values when the object is created:,You can also set default values inside the construct function using an if statement, this way if you forget to set one of the values, or create a new object with no arguments you get a default product:, PHP Object-Oriented PHP Basics (Retired) Properties and Methods Constructor Method

class Product < public $name = 'default name'; public $price = 0; public $desc = 'default description'; function __construct($name, $price, $desc) < $this->name=$name; $this->price=$price; $this->desc=$desc; > public function getInfo()< return $this->name; > > $p = new Product(); var_dump($p); 

Answer by Naomi Carrillo

The default value must be a constant expression, not (for example) a variable, a class member or a function call. ,Note: Arguments that are passed by reference may have a default value. , Argument lists may include the . token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; for example: , A function may define C++-style default values for scalar arguments as follows:

Making a cup of cappuccino. Making a cup of . Making a cup of espresso. 

Answer by Josue Bradley

Answer by Phoebe Bailey

Default values of uninitialized variables , Default values of uninitialized variables ,Although not necessary in PHP however it is a very good practice to initialize variables. Uninitialized variables have a default value of their type depending on the context in which they are used:, Outputting the Value of a Variable

Читайте также:  Javascript jquery click events

Unset AND unreferenced

var_dump($unset_var); // outputs NULL 
echo($unset_bool ? "true\n" : "false\n"); // outputs 'false' 
$unset_str .= 'abc'; var_dump($unset_str); // outputs 'string(3) "abc"' 
$unset_int += 25; // 0 + 25 => 25 var_dump($unset_int); // outputs 'int(25)' 

Float/double

$unset_float += 1.25; var_dump($unset_float); // outputs 'float(1.25)' 
$unset_arr[3] = "def"; var_dump($unset_arr); // outputs array(1) < [3]=>string(3) "def" > 
$unset_obj->foo = 'bar'; var_dump($unset_obj); // Outputs: object(stdClass)#1 (1) < ["foo"]=>string(3) "bar" > 

Answer by Ahmad Higgins

Setting Default Values for Function parameter,Function Parameters or Arguments,PHP allows us two ways in which an argument can be passed into a function: ,PHP allows us to set default argument values for function parameters. If we do not pass any argument for a parameter with default value then PHP will use the default set value for this parameter in the function call. Example:

function function_name($first_parameter, $second_parameter)
Ram is 15 years old Adam is 12 years old
The original value is still 10 The original value changes to 20

Answer by Maximus Ellis

PHPUnit assertTrue/assertFalse should be simplified to the corresponding dedicated assertion Code Smell,Files should not have too many lines of code Code Smell,Using command line arguments is security-sensitive Security Hotspot,Classes should not be coupled to too many other classes (Single Responsibility Principle) Code Smell

Noncompliant Code Example

function makeyogurt($type = "acidophilus", $flavor) // Noncompliant makeyogurt("raspberry")>> // Runtime error: Missing argument 2 in call to makeyogurt() 

Compliant Solution

function makeyogurt($flavor, $type = "acidophilus", ) makeyogurt("raspberry")>> // Works as expected 

Answer by Judah Benjamin

The default value must be a constant expression, not (for example) a variable, a class member or a function call. , By default, PHP will coerce values of the wrong type into the expected scalar type if possible. For example, a function that is given an integer for a parameter that expects a string will get a variable of type string. ,Note: As of PHP 5, arguments that are passed by reference may have a default value. , In PHP 5.6 and later, argument lists may include the . token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; for example:

Making a cup of cappuccino. Making a cup of . Making a cup of espresso. 

Источник

Default value of variables in PHP?

Example #1 Default values of uninitialized variables, Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive. , One important thing to note is that only named variables may be assigned by reference. , To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs ‘My name is Bob’ twice:

Читайте также:  Bitrix где подключаются css

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$

Answer by Jude Walters

Default values of uninitialized variables , Default values of uninitialized variables ,Although not necessary in PHP however it is a very good practice to initialize variables. Uninitialized variables have a default value of their type depending on the context in which they are used:, Outputting the Value of a Variable

Unset AND unreferenced

var_dump($unset_var); // outputs NULL 
echo($unset_bool ? "true\n" : "false\n"); // outputs 'false' 
$unset_str .= 'abc'; var_dump($unset_str); // outputs 'string(3) "abc"' 
$unset_int += 25; // 0 + 25 => 25 var_dump($unset_int); // outputs 'int(25)' 

Float/double

$unset_float += 1.25; var_dump($unset_float); // outputs 'float(1.25)' 
$unset_arr[3] = "def"; var_dump($unset_arr); // outputs array(1) < [3]=>string(3) "def" > 
$unset_obj->foo = 'bar'; var_dump($unset_obj); // Outputs: object(stdClass)#1 (1) < ["foo"]=>string(3) "bar" > 

Answer by Derrick Good

Depends on context. Generally, if inside of a class method or standard function, I know what variables are set because of the parameter signature. If I have to use the php extract() method to turn array key => val to variables, I’ll merge the input array with defaults so I know what variable will be set inside the scope it is used.,If the variable isn’t set to » by default it doesn’t seem like there would be a way around using isset() to avoid the warning.,Generally, if I don’t know what variables are set, I’ll look at how I can refactor my code to make it more solid — and of course, unit test!,Setting a variable to null is only useful for cases as with the one you circle around @everzet — having it as a function’s default variable.

Answer by Evelynn Gray

PHP allows you to define C++ style default argument values. In such case, if you don’t pass any value to the function, it will use default argument value.,Let’ see the simple example of using PHP default arguments in function.,JavaTpoint offers too many high quality services. Mail us on [email protected], to get more information about given services. ,JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] Duration: 1 week to 2 week

Hello Sonoo Hello Ram Hello Vimal 

Answer by Ivy Chan

You want a parameter to have a default value if the function’s caller doesn’t pass it. For example, a function to draw a table might have a parameter for border width, which defaults to 1 if no width is given. ,Assign the default value to the parameters inside the function prototype: ,If you want to assign a default of nothing, one solution is to assign the empty string to your parameter: ,The example in the Solution sets the default tag value to b, for bold. For example:

function wrap_html_tag($string, $tag = 'b') < return "$string"; >

Answer by Isabel Lu

I want to get a value from the session, but use a default if it is not defined. And ofcourse I want to circumvent the PHP notice.,Is there a way to do this without defining this function in every file?,The || operator is short circuit, it will not evaluate second operant if the first one be evaluated true. ,Now as far as an empty check, you could use @ to mute notices, I’m not sure of the technical ramifications, but you’re already doing your own checking while using this format:

Читайте также:  Css input select no border

You can write a function that does this

function get(&$var, $default) < if(isset($var)) return $var; return $default; >echo get($foo, "bar\n"); $foobar = "foobar"; echo get($foobar, "ERROR"); 

Answer by Bishop Moon

A function may define C++-style default values for scalar arguments as follows: ,Example #3 Use of default parameters in functions,Example #5 Incorrect usage of default function arguments, The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Making a cup of cappuccino. Making a cup of . Making a cup of espresso. 

Answer by Tessa Townsend

Note: as mentioned by Simon Scarfe and corrected by mseancole, PHP also has some special ternary syntax to do this:,This is more readable for two reasons : it’s easier to understand the syntax, but more importantly, it’s easier to see that you simply want a default value when there’s nothing. We don’t need the ‘else’ part which is confusing with the ternary operator.,(The ternary operator does make sense here since variable names are short and both branches of the condition are useful.),The one-liner is too long, and using the ternary operator on multiple lines is a bad idea: that’s what if-statement are for:

The one-liner is too long, and using the ternary operator on multiple lines is a bad idea: that’s what if-statement are for:

if (empty($newsItems[0]['image_url'])) < $newsItems[0]['image_url'] = '/img/cat_placeholder.jpg'; >

Note: as mentioned by Simon Scarfe and corrected by mseancole, PHP also has some special ternary syntax to do this:

$newsItems[0]['image_url'] = $newsItems[0]['image_url'] ?: 'img/cat_placeholder.jpg'; 

If you’re doing this only once or twice, then all is good, but otherwise you’d want to factorize it into a function, since you don’t repeat yourself, right? The simple way is:

function default_value($var, $default) < return empty($var) ? $default : $var; >$newsItems[0]['image_url'] = default_value($newsItems[0]['image_url'], '/img/cat_placeholder.jpg'); 

If we don’t care about the warning/error, can we do better? Yes we can! We’re writing the variable name twice, but passing by reference can help us here:

Источник

Оцените статью