I understand that wanting to update or remove a constant is the exact opposite if what it is meant for, but here is my problem.
I want to be able to format a value in same same fashion that a constant does. i.e.: echo foo;
Where it can just be plain text, instead of echoing a variable like $foo.
It may seem like a silly thing to want to do, but I am hoping to create use out of it. However, if this is not possible, I guess that is that.
PS. I 'would' just define it as a constant, however I want it to be able to update (like re-defining it during a foreach).
Sort of. The first one must be case-insensitive:
define("myConstant", "blah", true);
print myConstant; // blah
define("myConstant", "xxxx"); // No warning outputted
print myConstant; // xxxx
But, DON'T DO THIS! The whole point of a constant is that it's constant. Although you seem to sort of recognize this, what is wrong with that extra $ sign, really, versus a much more clear code style?
According to http://www.php.net/manual/en/function.define.php#92327, you can redefine constants on the fly if necessary.
define("FIRST_CONSTANT", 'my 1st value', true);
echo FIRST_CONSTANT;
// my 1st value
define('FIRST_CONSTANT', 'my 2nd value');
echo FIRST_CONSTANT;
// my 2nd value
You could use the name of a function like this:
<?php
function hello(){ return "bla"; }
$a = hello;
$b = $a();
echo $b;
?>
Related
I don't think I understand how PHP output buffering works well enough to know whether this is possible: I want to do the following, in this order:
Declare a PHP variable $foo
Begin and end an output buffer to declare a variable $bar
Use the variable $foo
When I try to use $foo the second time, it appears I inadvertently cleared it.
Code example:
<?php
$foo = 'some value';
ob_start();
include('some_file.php');
//I want to use output buffering since some_file.php has a number of echo statements that I want to concatenate into one variable. Maybe there's a better way?
$bar = ob_get_clean();
ob_end_flush();
echo $bar;
echo $foo;
?>
In the example above, $bar works fine but $foo is undefined at the end. I don't think I understand the underlying concepts well enough to know exactly what's going on in the code here. I want to be able to use the buffer (or some other method?) to make all the echo statements in some_file.php go to a single string, while preserving the variables from the previous PHP code. Is there a way to do this?
In the example above, $bar works fine but $foo is undefined at the end
You are probably unsetting it inside some_file.php. Your script works fine otherwise. You can also return the output from the other file via return inside some_file.php:
// some_file.php
...
return $output;
// main file
...
$bar = include('some_file.php');
The title might be a bit confusing, but w/e.
Is it possible to do something like this?
define('test_1', 'test1');
define('test_2', 'test2');
define('test_3', 'test3');
$test='2';
echo test_$test;
I simply want to echo one of those defined constants (in this case 2) depending on what $test is, without using if() or switch().
You should be sorted with the following:
echo constant('test_'.$test);
Earlier today I tried to do this:
Example 1:
<?php
echo $myVar || "rawr";
?>
I thought this might print out $myVar if it was set, and print "rawr" if not.
It printed a 1, I assume this is the result of the OR test.
What I then tried was this:
Example 2:
<?php
if ($myVar)
{
echo $myVar;
}
else
{
echo "rawr";
}
?>
Which is what I was trying to accomplish.
I think I understand why the first prints the results of the OR test rather than one of the variables, and also why I tried it - been spending some time on the bash shell recently :)
Can anyone tell me if there is a way to perform the text in example #2 but in similar syntax to example #1?
PHP 5.3:
echo $myVar ?: 'rawr';
Pre 5.3:
echo $myVar ? $myVar : 'rawr';
If $myVar may not be set you'd have to use isset($myVar) and $myVar as the condition (which then wouldn't work with the shorthand ?: syntax, as this would echo 1 if it was set, rather than the value).
echo (isset($myVar) and $myVar) ? $myVar : 'rawr';
PHP is notoriously inelegant in this department, and there really is no good way of making this test.
As a general solution, you 'd need to use the ternary operator as in empty($var) ? "rawr" : $var. However, in practice what happens is that you have one of two scenarios:
1. Your own variable
In this case where you define the variable yourself, the best solution is to just give it a known default value at the place you define it (possibly with the ternary operator).
2. Inside an array
If the array is one that should not be touched like one of the superglobals, then you can wrap the test inside a function (pretty much that's what everyone does).
If the array is one under your jurisdiction but it comes from an external source, you can use the "add the defaults" trick:
$incoming = array(...);
$defaults = array("foo" => "bar");
// Inject the defaults into $incoming without overwriting existing values
$incoming += $defaults;
At this point you know for a fact that every key inside $defaults also exists inside $incoming.
In PHP 5.3+ it is possible to leave out the second argument:
echo $myVar ?: 'rawr';
This is probably closest to what you want.
Try this:
echo $myVar = ($myVar) ? $myVar : 'rawr';
or
echo $myVar ? $myVar : 'rawr';
I think you want to use something like var_dump($varname) or isset($varname) ?
it's matter of operator precedence. you can't do that.
two points as a food for thought
if $myVar is not set, you'll get an error message, not "wawr";
by the time you're going to echo some variables, every one of them should be defined and have value. That will make your template clean and readable.
Try
echo ($myVar != null ? $myVar : "Rawr!");
Setting variable values inside a function call - I don't see this a lot, is this considered good practice?
function myUpdate($status){
...
}
myUpdate($status = 'live');
I personally like it because it's more descriptive. I see it more frequently the other way around, ie., assigning a default value in the function definition.
That's a very bad idea, because it's basically code obfuscation. php does not support keyword arguments, and that can lead to weird stuff. Case in point:
function f($a, $b){
echo 'a: ' . $a . "\n";
echo 'b: ' . $b . "\n";
}
f($b='b-value', $a='a-value');
This program does not only output
a: b-value
b: a-value
but also defines the variables $b and $a in the global context. This is because
f($b='b-value', $a='a-value');
// is the same thing as ...
$b = 'b-value';
$a = 'a-value';
f($b, $a);
There are a few good practices one can do to make remembering method arguments easier:
Configure your editor/IDE to show the signature of functions on highlight.
If a function has lots of arguments that describe some kind of state, consider moving it into an *objec*t (that holds the state instead)
If your function just needs lots of arguments, make it take an array for all non-essential ones. This also allows the method caller not to worry at all about the multitude of options, she just needs to know the ones she's interested in.
All kidding aside, seriously why do you use it? You have to realize it's something totally different than assigning a default value. What you're doing here is assigning the value to a variable, and then passing that variable to the function. The result is, that after the function call, the $status varialbe is still defined.
myUpdate( $status = 'live' );
echo $status; // "live"
Even if this is what you want, I'd say it's less descriptive than just splitting it out in two lines.
No, it's not because it's extra code. Try:
myUpdate('live' /*status*/, 42 /*maxTries*/);
Or if you really wanted named parameters, you could use a map:
myUpdate(array(
'status' => 'live'
));
Normally it would kill type safety, but PHP doesn't have any, anyway.
Well, default value is different thing.
// if you call myUpdate without argument, it will have $status with value live
function myUpdate($status = 'live'){
}
Calling this:
myUpdate($status = 'live');
is equivalent to:
myUpdate('live');
with the only difference being that after the call, if you call it like myUpdate($status = 'live'); you will keep the $status var with value live in the scope where you called the function, not inside it.
But IMHO its much more readable to do it like this:
$status = 'live';
myUpdate($status);
What does this code mean? Is this how you declare a pointer in php?
$this->entryId = $entryId;
Variable names in PHP start with $ so $entryId is the name of a variable.
$this is a special variable in Object Oriented programming in PHP, which is reference to current object.
-> is used to access an object member (like properties or methods) in PHP, like the syntax in C++.
so your code means this:
Place the value of variable $entryId into the entryId field (or property) of this object.
The & operator in PHP, means pass reference. Here is a example:
$b=2;
$a=$b;
$a=3;
print $a;
print $b;
// output is 32
$b=2;
$a=&$b; // note the & operator
$a=3;
print $a;
print $b;
// output is 33
In the above code, because we used & operator, a reference to where $b is pointing is stored in $a. So $a is actually a reference to $b.
In PHP, arguments are passed by value by default (inspired by C). So when calling a function, when you pass in your values, they are copied by value not by reference. This is the default IN MOST SITUATIONS. However there is a way to have pass by reference behaviour, when defining a function. Example:
function plus_by_reference( &$param ) {
// what ever you do, will affect the actual parameter outside the function
$param++;
}
$a=2;
plus_by_reference( $a );
echo $a;
// output is 3
There are many built-in functions that behave like this. Like the sort() function that sorts an array will affect directly on the array and will not return another sorted array.
There is something interesting to note though. Because pass-by-value mode could result in more memory usage, and PHP is an interpreted language (so programs written in PHP are not as fast as compiled programs), to make the code run faster and minimize memory usage, there are some tweaks in the PHP interpreter. One is lazy-copy (I'm not sure about the name). Which means this:
When you are coping a variable into another, PHP will copy a reference to the first variable into the second variable. So your new variable, is actually a reference to the first one until now. The value is not copied yet. But if you try to change any of these variables, PHP will make a copy of the value, and then changes the variable. This way you will have the opportunity to save memory and time, IF YOU DO NOT CHANGE THE VALUE.
So:
$b=3;
$a=$b;
// $a points to $b, equals to $a=&$b
$b=4;
// now PHP will copy 3 into $a, and places 4 into $b
After all this, if you want to place the value of $entryId into 'entryId' property of your object, the above code will do this, and will not copy the value of entryId, until you change any of them, results in less memory usage. If you actually want them both to point to the same value, then use this:
$this->entryId=&$entryId;
No, As others said, "There is no Pointer in PHP." and I add, there is nothing RAM_related in PHP.
And also all answers are clear. But there were points being left out that I could not resist!
There are number of things that acts similar to pointers
eval construct (my favorite and also dangerous)
$GLOBALS variable
Extra '$' sign Before Variables (Like prathk mentioned)
References
First one
At first I have to say that PHP is really powerful language, knowing there is a construct named "eval", so you can create your PHP code while running it! (really cool!)
although there is the danger of PHP_Injection which is far more destructive that SQL_Injection. Beware!
example:
Code:
$a='echo "Hello World.";';
eval ($a);
Output
Hello World.
So instead of using a pointer to act like another Variable, You Can Make A Variable From Scratch!
Second one
$GLOBAL variable is pretty useful, You can access all variables by using its keys.
example:
Code:
$three="Hello";$variable=" Amazing ";$names="World";
$arr = Array("three","variable","names");
foreach($arr as $VariableName)
echo $GLOBALS[$VariableName];
Output
Hello Amazing World
Note: Other superglobals can do the same trick in smaller scales.
Third one
You can add as much as '$'s you want before a variable, If you know what you're doing.
example:
Code:
$a="b";
$b="c";
$c="d";
$d="e";
$e="f";
echo $a."-";
echo $$a."-"; //Same as $b
echo $$$a."-"; //Same as $$b or $c
echo $$$$a."-"; //Same as $$$b or $$c or $d
echo $$$$$a; //Same as $$$$b or $$$c or $$d or $e
Output
b-c-d-e-f
Last one
Reference are so close to pointers, but you may want to check this link for more clarification.
example 1:
Code:
$a="Hello";
$b=&$a;
$b="yello";
echo $a;
Output
yello
example 2:
Code:
function junk(&$tion)
{$GLOBALS['a'] = &$tion;}
$a="-Hello World<br>";
$b="-To You As Well";
echo $a;
junk($b);
echo $a;
Output
-Hello World
-To You As Well
Hope It Helps.
That syntax is a way of accessing a class member. PHP does not have pointers, but it does have references.
The syntax that you're quoting is basically the same as accessing a member from a pointer to a class in C++ (whereas dot notation is used when it isn't a pointer.)
To answer the second part of your question - there are no pointers in PHP.
When working with objects, you generally pass by reference rather than by value - so in some ways this operates like a pointer, but is generally completely transparent.
This does depend on the version of PHP you are using.
You can simulate pointers to instantiated objects to some degree:
class pointer {
var $child;
function pointer(&$child) {
$this->child = $child;
}
public function __call($name, $arguments) {
return call_user_func_array(
array($this->child, $name), $arguments);
}
}
Use like this:
$a = new ClassA();
$p = new pointer($a);
If you pass $p around, it will behave like a C++ pointer regarding method calls (you can't touch object variables directly, but that's evil anyways :) ).
entryId is an instance property of the current class ($this)
And $entryId is a local variable
Yes there is something similar to pointers in PHP but may not match with what exactly happens in c or c++.
Following is one of the example.
$a = "test";
$b = "a";
echo $a;
echo $b;
echo $$b;
//output
test
a
test
This illustrates similar concept of pointers in PHP.
PHP passes Arrays and Objects by reference (pointers). If you want to pass a normal variable Ex. $var = 'boo'; then use $boo = &$var;.
PHP can use something like pointers:
$y=array(&$x);
Now $y acts like a pointer to $x and $y[0] dereferences a pointer.
The value array(&$x) is just a value, so it can be passed to functions, stored in other arrays, copied to other variables, etc. You can even create a pointer to this pointer variable. (Serializing it will break the pointer, however.)