use of this in PHP - php

I am new to PHP and need your help here. I know the basic functionality of this in PHP.
class SwapClass
{
public $num1 = 0;
public $num2 = 0;
function __construct($val1,$val2)
{
echo "In constructor!!" . "<br />";
$num1 = $val1;
$num2 = $val2;
}
public function display()
{
echo "1st value : " . $num1 . "<br />2nd value : " . $num2;
}
}
This is my class. I called it as:
$obj = new SwapClass(2,3);
$obj->display();
The values never come to the display() method. I tried echoing it in the constructor. It's confirmed that values are coming. I then modified the code to:
class SwapClass
{
public $num1 = 0;
public $num2 = 0;
function __construct($val1,$val2)
{
echo "In constructor!!" . "<br />";
$this->num1 = $val1;
$this->num2 = $val2;
}
public function display()
{
echo "1st value : " . $this->num1 . "<br />2nd value : " . $this->num2;
}
}
It works fine now. Why does can't the variables be accessed without this?
Is this used for disambiguation? In my example I have just one object. So what is the problem?

Any member of class is recognized buy using $this in class.
Otherwise it will be treated as local variable where it is being used.
It does not depend on number of object of class, You need to use it for one object as well as for hundreds and more.
http://tournasdimitrios1.wordpress.com/2010/10/11/using-the-keyword-this-in-php/

Related

How to cache Methods for one process?

I'm trying to cache an Object's method, so every time I call the Class and the method, it won't process again after first time.
Here is what I'm trying to achieve,
class App {
public $data = null;
public function print() {
if ( $this->data === null ) {
$this->data = "First time.";
}
else {
$this->data = "After first time.";
}
return $this->data;
}
}
$data = new App();
echo $data->print() . "<br>";
echo $data->print() . "<br>";
$data2 = new App();
echo $data2->print() . "<br>";
echo $data2->print() . "<br>";
Result
First time.
After first time.
First time.
After first time.
As you can see, it's processing the print() method again when I call it again in $data2.
Is it possible to cache so result will be
First time.
After first time.
After first time.
After first time.
For get your required constant output you need to
change the public variable inside the class to as static variable
Because public static variables share all the available instances of that class each time.
class App {
public static $data = null;
public function print() {
if ( self::$data === null ) {
self::$data = "First time.";
}
else {
self::$data = "After first time.";
}
return self::$data;
}
}
$data = new App();
echo $data->print() . "<br>";
echo $data->print() . "<br>";
$data2 = new App();
echo $data2->print() . "<br>";
echo $data2->print() . "<br>";
Result will be :
First time.
After first time.
After first time.
After first time.

Simple PHP class

I am learning php and created the below class, but I can't seem to figure out why it giving me the below errors which says:
144
Warning: Missing argument 1 for setters::set_a(), called in C:\xampp\htdocs\php\accessmod2.php on line 19 and defined in C:\xampp\htdocs\php\accessmod2.php on line 9
Notice: Undefined variable: value in C:\xampp\htdocs\php\accessmod2.php on line 11
<?php
class setters{
private $a = 144;
public function get_a(){
return $this->a;
}
public function set_a($value){
$this->a = $value;
}
}
$example = new setters();
echo $example->get_a()."<br />";
$example->set_a(15)."<br />";
echo $example->set_a()."<br />";
?>
You have to use a parameter for the set() function. But in your case, I think you just want to see if the set() function have work. So use the get() function.
So change to this :
echo $example->get_a()."<br />";
$example->set_a(15)."<br />";
echo $example->get_a()."<br />";
And the result is :
144
15
Check your last line:
echo $example->set_a()."<br />";
set_a() requires a parameter but it is empty. If you change it like this, it will work:
echo $example->set_a('someparameterhere')."<br />";
Your second call to ->set_a requires a parameter :
<?php
class setters{
private $a = 144;
public function get_a(){
return $this->a;
}
public function set_a($value){
$this->a = $value;
}
}
$example = new setters();
echo $example->get_a()."<br />";
$example->set_a(15)."<br />";
$example->set_a(23)."<br />"; // ◄■■■ PARAMETER FOR "SET_A".
?>
You can also use an "optional" parameter :
<?php
class setters{
private $a = 144;
public function get_a(){
return $this->a;
}
public function set_a( $value = -1 ){ // ◄■■■ OPTIONAL PARAMETER.
$this->a = $value;
}
}
$example = new setters();
echo $example->get_a()."<br />";
$example->set_a()."<br />"; // ◄■■■ OPTIONAL PARAMETER ($a = -1).
echo $example->get_a()."<br />"; // ◄■■■ NEW VALUE = -1.
?>
You are calling set_a twice.
After set, you need call get_a to show the value.
echo $example->get_a()."<br />";
$example->set_a(15)."<br />";
echo $example->get_a()."<br />";

Variable arrays in class context

I am trying to accomplish a simple class method where the user submit its name to a form and it returns a greeting message for every name on the variable array, such as "Welcome John", "Welcome Mike", etc...
Doing this as a regular function is easy:
$arr = array('Mike', 'John', 'Molly', 'Louis');
function Hello($arr) {
if(is_array($arr)) {
foreach($arr as $name) {
echo "Hello $name" . "<br>";
}
} else {
echo "Hello $arr";
}
}
Hello($arr);
However, I can't make it work in class context:
$arr = array('Mike', 'John', 'Molly', 'Louis');
class greetUser {
public $current_user;
function __construct($current_user) {
$this->current_user = $current_user;
}
public function returnInfo() {
if(is_array($this->current_user)) {
foreach($this->current_user as $name) {
echo "Welcome, " . $name;
}
} else {
echo "Welcome, " . $this->current_user;
}
}
}
$b = new greetUser(''.$arr.'');
$b->returnInfo();
replace your $b = new greetUser(''.$arr.''); with $b = new greetUser($arr); and it will work :)
I was commiting a very silly mistake, as users pointed out, I was concatenating the variable when it was not necessary!

Variable inside the link

Would someone be able to help me with some php.
I am new to this and I am trying to solve the puzzle.
I am trying to combine the input data that user has provided with the link so that final output displays record for the user whose regid was provided by user via input text field.
Here is some code I came up with that obviously does not work.
class Fields_View_Helper_FieldStats extends Fields_View_Helper_FieldAbstract
{
public function fieldStats($subject, $field, $value)
{
$userid = preg_replace(trim($value->value));
// create user's profile address using their username/userid
$stats = $userid;
echo '<div style="margin:0px auto;"><script type="text/javascript" src="http://e1.statsheet.com/embed/';
return $this->view->string()->chunk($value->value);
echo '/1/NuNes.js"></script></div>';
}
}
To concatenate a string in PHP do this (note the periods, which are doing the work)
$str = "Line 1 " . $somevar . " Line 2";
return $str
Issuing a return terminates your function. I would build one string inside a variable then return that variable
The return ends the method, because it returns the value to the caller.
<?php
function fn() {
return "bar";
}
echo fn(); // will output bar
function fn2() {
echo "foo";
return "bar";
}
echo fn2(); // will output foobar
function fn3() {
return "foo" . fn();
}
echo fn3(); // will output foobar as well
?>
And here's how you can connect those three lines in the code snippet you posted:
<?php
class Fields_View_Helper_FieldStats extends Fields_View_Helper_FieldAbstract
{
public function fieldStats($subject, $field, $value)
{
$userid = preg_replace(trim($value->value));
// create user's profile address using their username/userid
$stats = $userid;
return
'<div style="margin:0px auto;"><script type="text/javascript" src="http://e1.statsheet.com/embed/' .
$this->view->string()->chunk($value->value) .
'/1/NuNes.js"></script></div>'
;
}
}
?>
And here's how you can concatenate strings:
<?php
$string1 = 'foo ' . fn() . ' bar';
$string2 = "foo 2" . fn() . " bar";
?>
And here's how you can embed stuff in variables (faster):
<?php
$string1 = fn();
$string1 = "foo {$string1} bar";
// Or with an object
class Foo {
public function fn(){}
}
$foo = new Foo();
$string1 = "foo {$foo->fn()} bar";
?>

Is there a way to output the definition of a function in PHP?

function func() {
// ...
}
I have the function name "func", but not its definition.
In JavaScript, I'd just use alert() to see the definition.
Is there a similar function in PHP?
You can use the methods getFileName(), getStartLine(), getEndLine() defined in ReflectionFunctionAbstract to read the source code of functions/methods from their source file (if there is any).
e.g. (without error handling)
<?php
printFunction(array('Foo','bar'));
printFunction('bar');
class Foo {
public function bar() {
echo '...';
}
}
function bar($x, $y, $z) {
//
//
//
echo 'hallo';
//
//
//
}
//
function printFunction($func) {
if ( is_array($func) ) {
$rf = is_object($func[0]) ? new ReflectionObject($func[0]) : new ReflectionClass($func[0]);
$rf = $rf->getMethod($func[1]);
}
else {
$rf = new ReflectionFunction($func);
}
printf("%s %d-%d\n", $rf->getFileName(), $rf->getStartLine(), $rf->getEndLine());
$c = file($rf->getFileName());
for ($i=$rf->getStartLine(); $i<=$rf->getEndLine(); $i++) {
printf('%04d %s', $i, $c[$i-1]);
}
}
I don't know of one.See code at bottom. There is a function to list all the defined functions. There's another to get the values of all the arguments to the current function, and the number of arguments. And there's one to see if a function exists. But there doesn't seem to be one to name the current function, nor any means of listing formal parameters.
Even when a runtime error occurs, it doesn't list a call stack, nor state the function that's active:
PHP Warning: Division by zero in t.php on line 6
Edit: For the code to identify where it is, add this:
echo "At line " .__LINE__ ." of file " . __FILE__ ."\n";
It gives the output
At line 7 of file /home/wally/t.php
Edit 2: I found this function in my code which looks to be what you want:
function traceback ($showvars)
{
$s = "";
foreach (debug_backtrace($showvars) as $row)
{
$s .= "$row[file]#$row[line]: ";
if(isset($row['class']))
$s .= "$row[class]$row[type]$row[function]";
else $s .= "$row[function]";
if (isset($row['args']))
$s .= "('" . join("', '",$row['args']) . "')";
$s .= "<br>\n";
}
return $s;
}
For example, it produces:
[wally#zf ~]$ php -f t.php
/home/wally/t.php#24: traceback('1')<br>
/home/wally/t.php#29: t('1', '2', '3')<br>
/home/wally/t.php#30: x('2', '1')<br>
/home/wally/t.php#31: y('2', '1')<br>
/home/wally/t.php#33: z('1', '2')<br>

Categories