This question already has answers here:
When would you use the $this keyword in PHP?
(12 answers)
Closed 9 years ago.
I tried to create a basic class with a function. Once an instance of the class is created new BaseClass("hello") then the constructor function saves the parameter to a variable.
The ->ret_text() should return with this variable, but it doesn't works. The error is: unexpected T_OBJECT_OPERATOR
class BaseClass {
var $txt;
function __construct($text) {
$txt = $text;
}
public function ret_text() {
return $txt;
}
}
echo (new BaseClass("hello"))->ret_text();
You should access your class variables with $this->variableName where $this refers to the class you are in.
In your example $txt is not the class variable $txt but only a variable for the current function (__construct(), ret_text() or something else). Also you can't call a method directly after the initialization of the class, i.e. (new Class())->methodName(); will not work for PHP version < 5.4. However, it will work for PHP version => 5.4.
Instead try this:
class BaseClass {
var $txt;
function __construct($text) {
$txt = 'This is a variable only for this method and it\'s not $this->txt.';
$this->txt = $text;
}
public function ret_text() {
$txt = 'This is a variable only for this method and it\'s not $this->txt.';
return $this->txt;
}
}
$bc = new BaseClass("hello");
echo $bc->ret_text();
Related
This question already has answers here:
How to echo a custom object in PHP?
(4 answers)
Closed 3 years ago.
Please i need to create a functions and call them in one line using -> between them
I have this code but it doesn't run
<?php
class A {
public $a2;
public $b2;
public function mohamed($a){
$this->a2 = $a;
return $this ;
}
public function test($b){
$this->b2 = $b;
return $this ;
}
}
$class = new A();
echo $class->mohamed('name')->test('mohamed');;
?>
Since your class doesn't have a __toString() method, you cannot echo the class object itself.
So you have a few alternatives here, either declare a __toString() method that prints what you want it to, or print the variables separately.
Example using the magic-method __toString() (demo at https://3v4l.org/NPp2L) - you can now echo $class.
public function __tostring() {
return "A2 is '".$this->a2."' and B2 is '".$this->b2."'";
}
Alternative two is to not print the class itself, but get the properties of the class instead. Since they are public, you don't need a getter-method to use them in the public scope.
$class = new A();
$class->mohamed('name')->test('mohamed');;
echo $class->a2." and ".$class->b2;
Demo at https://3v4l.org/nHeP9
If I run your code the error explains the problem :
Object of class A could not be converted to string
Your function test() returns $this, a class A object which can not be echoed.
Try implement a __toString() function, or use a var_dump() instead of your echo to check your object's properties.
No matter what, your code and your chaining is working fine.
Actually, above code is running but you can not echo an object also you can try "var_dump()" instead of "echo".
var_dump($class->mohamed('name')->test('mohamed'));
Try this:
<?php
class A {
public $a2;
public $b2;
public function mohamed($a){
$this->a2 = $a;
return $this ;
}
public function test($b){
$this->b2 = $b;
return $this ;
}
}
$class = new A();
var_dump($class);
?>
This question already has answers here:
How to call a closure that is a class variable?
(2 answers)
Closed 4 years ago.
$f = function($v) {
return $v + 1;
}
echo $f(4);
// output -> 5
The above works perfectly fine. However, I cannot reproduce this correctly when f is a property of a class.
class MyClass {
public $f;
public function __construct($f) {
$this->f = $f;
}
public function methodA($a) {
echo $this->f($a);
}
}
// When I try to call the property `f`, PHP gets confused
// and thinks I am trying to call a method of the class ...
$myObject = new myClass($f);
$myObject->methodA(4);
The above will result in an error:
Call to undefined method MyClass::f()
I think the problem is that it is trying to make sense of
echo $this->f($a);
And as you've found it wants to call a member function f in the class. If you change it to
echo ($this->f)($a);
It interprets it as you want it to.
PHP 5.6
Thanks to ADyson for the comment, think this works
$f = $this->f;
echo $f($a);
While Nigel Ren's answer (https://stackoverflow.com/a/50117174/5947043) will work in PHP 7, this slightly expanded syntax will work in PHP 5 as well:
class MyClass {
public $f;
public function __construct($f) {
$this->f = $f;
}
public function methodA($a) {
$func = $this->f;
echo $func($a);
}
}
$f = function($v) {
return $v + 1;
};
$myObject = new myClass($f);
$myObject->methodA(4);
See https://eval.in/997686 for a working demo.
This question already has answers here:
Get variable name of object inside the object php
(3 answers)
Closed 8 years ago.
I would like to know, if it is possible in PHP (using reflection or not) to get the variable name abc inside the class method in this example.
class Example
{
public function someMethod()
{
// once this method is called, I want it to echo `abc` in this example
}
}
Now, when I call the method using a variable name like
$abc= (new Example)->someMethod();
echo $abc; // abc
I would like to see the name of the variable, 'foo' shown, in other words the class would have to be aware of the variable name, when returning the methods contents.
I always pass in the name of the variable it will be assigned to if it it is required
class myclass {
var $myname;
function __construct($myname='no name') {
$this->myname=$myname;
#print "In BaseClass constructor\n";
}
function sayHello()
{
return "hello from " . $this->myname . "\n";
}
}
usage:
$myVar = new myclass("myVar");
$yourVar = new myclass("yourVar");
echo $myVar->sayHello();
echo $yourVar->sayHello();
This question already has answers here:
php call class function by string name
(6 answers)
Closed 8 years ago.
In PHP5, variables can be evaluated as functions1 such as:
function myFunc() {
echo "whatever";
}
$callableFunction = 'myFunc';
$callableFunction(); // executes myFunc()
Is there any syntax for assigning object member functions to a variable such as:
class MyClass {
function someCall() {
echo "yay";
}
}
$class = new MyClass();
// what I would like:
$assignedFunction = $class->someCall; // but I tried and it returns an error
$memberFunc = 'someCall';
$class->$memberFunc(); // I know this is valid, but I want a single variable to be able to be used to call different functions - I don't want to have to know whether it is part of a class or not.
// my current implementation because I don't know how to do it with anonymous functions:
$assignedFunction = function() { return $class->someCall(); } // <- seems lengthy; would be more efficient if I can just assign $class->someCall to the variable somehow?
$assignedFunction(); // I would like this to execute $class->someCall()
There is a way, but for php 5.4 and above...
class MyClass {
function someCall() {
echo "yay";
}
}
$obj = new Myclass();
$ref = array($obj, 'someCall');
$ref();
Hm.. actually it works for static too, just use the reference by name..
class MyClass {
static function someCall2() {
echo "yay2";
}
}
$ref = array('MyClass', 'someCall2');
$ref();
And for nonstatic this notation works as well. It creates a temporary instance of the class. So, this is what you need, only you need php 5.4 and above )
The PHP 5.4 solution above is good. If you need PHP 5.3, I don't think you can do much better than the anonymous function approach, but you could wrap that into a function that acts very similar to the PHP 5.4 method:
function buildCallable($obj, $function)
{
return function () use ($obj, $function) {
$args = func_get_args();
return call_user_func_array(array($obj, $function), $args);
};
}
//example
class MyClass
{
public function add($x, $y)
{
return $x + $y;
}
public static function multiply($x, $y)
{
return $x * $y;
}
}
//non-static methods
$callable = buildCallable(new MyClass(), 'add');
echo $callable(32, 10);
//static methods
$callable = buildCallable('MyClass', 'multiply');
echo $callable(21, 2);
This should work for any number of arguments to any (publicly visible) method.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
From the string name of a class, can I get a static variable?
Somewhere in a parent class, I need to find the value of a static variable of one of the possible child classes, determined by the current instance.
I wrote:
$class = get_class($this);
$value = isset($class::$foo['bar']) ? $class::$foo['bar'] : 5;
In this example, the subclass whose name is in $class has a public static $foo.
I know using $class::$foo['bar'] is not a very beautiful piece of code, but it gets the job done on PHP 5.3.4.
In PHP 5.2.6 though, I am getting a syntax error:
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting ',' or ')'
Is there an alternative way that would work on PHP 5.2.4+ that would get the same thing done?
EDIT: Reflection is better.
You can try the get_class_vars method. No access to PHP 5.2.6, but this works in 5.2.11...
class Test {
public static $foo;
function __construct() {
echo("...Constructing...<br/>");
Test::$foo = array();
Test::$foo['bar'] = 42;
}
function __toString() {
return "Test";
}
}
$className = 'Test';
$class = new $className();
$vars = get_class_vars($className);
echo($vars['foo']['bar'] . "<br/>");
Output:
...Constructing...
42
The reason that this does not work in PHP 5.2, is because before PHP 5.3 you are not allowed to use variables in the classname. So, if possible use eval for this.
eval('$result = ' . $c . '::$foo[\'bar\'];');
echo $result;
Otherwise, you're forced to use a function in the child class to receive the value. For example:
class MyParent {
public function __construct() {
$var = $this->_getVariable();
echo $var['bar'];
}
}
class MyChild extends MyParent {
static $var = array('bar' => 'foo');
protected function _getVariable() {
return self::$var;
}
}
new MyChild();
class Bar1 {
static $var = array('index' => 'value');
}
class Bar2 extends Bar1 {
}
class Foo extends Bar2 {
static $var = array('index' => 'value in Foo');
public function __construct() {
echo parent::$var['index'];
}
}
$foo = new Foo();
will output 'value', but not 'value in Foo'
Hope, that's what you are looking for.
You can get class static/call static method in the class you are working in using self key word or for parent class using parent. You can get that error on php 5.2.6 because of changes in get_class function in PHP 5.3.0