How to echo an object? [duplicate] - php

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);
?>

Related

Using local variable from call in a function

After 9 hours of struggling to get this right, I have turned to the internet for help. I can't seem to find any relevant answers doing a Google search.
I currently have a class called Test. Test accepts a single argument.
<?php
class test {
private $varpassed;
public function getVarpas() {
return $this->varpassed;
}
Public function setVarpas($value) {
$this->varpassed= $value;
}
public function stringGen(){
$testvar = $this->varpassed;
echo $testvar;
}
}
The stringGen function should return the $varpassed variable whenever its called. The value for $varpassed is set using the setVarpas function. However, when ever I call the stringGen() method I only seem to be getting the following error:
Fatal error: Using $this when not in object context in file.php line 14.
Pointing to this line:
$testvar = $this->varpassed;
Is there any other way to pass the variable to the stringGen method? I've tried using:
self::$this->varpassed;
Which also throws an error.
first create an instance of the object (so you can use $this in the context), for example:
$test = new test();
then you can call:
$test->setVarpas('Hello World!');
now you can call:
$test->stringGen();
you have to do something like this
$var = new test();
$var->setVarpas("Hello");
$var->stringGen(); // this will echo Hello
$this is used when you are withing class. outside class you have to use class object.
1) Change this: class test() to class test
2) Create and instance first something like $t1 = new test();
3) Call the function $t1->setVarpas(5);
4) Now you can call the function $t1->stringGen();
Fixed:
<?php
class test
{
private $varpassed;
public function getVarpas() {
return $this->varpassed;
}
Public function setVarpas($value) {
$this->varpassed= $value;
}
public function stringGen(){
$testvar = $this->varpassed;
echo $testvar;
}
}
$t1 = new test();
$t1->setVarpas(5);
$t1->stringGen();
OUTPUT:
5
You should not declare a class with parentheses.
Use
class test {
instead of
class test(){

PHP - Can you assign a member function to a variable? [duplicate]

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.

Convert static method to lambda in PHP

I want to get static method from class and copy it to variable.
This is non-working example illustrating my question:
class foo
{
public static function bar($argument){ return 2*$argument; }
}
$class = new ReflectionClass('foo');
// here is no ReflectionMethod::getClosure() method in reality
$lambda = $class->getMethod('bar')->getClosure();
echo $lambda(3);
So my question: is this possible by any normal way? I find only one way for now. I can parse source file, get method source from it and convert it using create_function() but it's too perverse.
Just wrap it with closure.
$lamda = function($argument){return foo::bar($argument);};
Or you can try to use something like this
function staticMethodToClosure($class, $method) {
return function($argument)use($class, $method){return $class::$method($argument);};
}
An array in the format array($className, $methodName) is invokable as a static method call so this may work for you.
class foo
{
public static function bar($argument){ return 2*$argument; }
public static function getStaticFunction($arg){
return array("foo", $arg);
}
}
$a = foo::getStaticFunction("bar");
echo $a(5); // echos 10

PHP - passing variables to classes

I trying to learn OOP and I've made this class
class boo{
function boo(&another_class, $some_normal_variable){
$some_normal_variable = $another_class->do_something();
}
function do_stuff(){
// how can I access '$another_class' and '$some_normal_variable' here?
return $another_class->get($some_normal_variable);
}
}
and I call this somewhere inside the another_class class like
$bla = new boo($bla, $foo);
echo $bla->do_stuff();
But I don't know how to access $bla, $foo inside the do_stuff function
<?php
class Boo
{
private $bar;
public function setBar( $value )
{
$this->bar = $value;
}
public function getValue()
{
return $this->bar;
}
}
$x = new Boo();
$x->setBar( 15 );
print 'Value of bar: ' . $x->getValue() . PHP_EOL;
Please don't pass by reference in PHP 5, there is no need for it and I've read it's actually slower.
I declared the variable in the class, though you don't have to do that.
Ok, first off, use the newer style constructor __construct instead of a method with the class name.
class boo{
public function __construct($another_class, $some_normal_variable){
Second, to answer your specific question, you need to use member variables/properties:
class boo {
protected $another_class = null;
protected $some_normal_variable = null;
public function __construct($another_class, $some_normal_variable){
$this->another_class = $another_class;
$this->some_normal_variable = $some_normal_variable;
}
function do_stuff(){
return $this->another_class->get($this->some_normal_variable);
}
}
Now, note that for member variables, inside of the class we reference them by prefixing them with $this->. That's because the property is bound to this instance of the class. That's what you're looking for...
In PHP, constructors and destructors are written with special names (__construct() and __destruct(), respectively). Access instance variables using $this->. Here's a rewrite of your class to use this:
class boo{
function __construct(&another_class, $some_normal_variable){
$this->another_class = $another_class;
$this->some_normal_variable = $another_class->do_something();
}
function do_stuff(){
// how can I access '$another_class' and '$some_normal_variable' here?
return $this->another_class->get($this->some_normal_variable);
}
}
You need to capture the values in the class using $this:
$this->foo = $some_normal_variable

PHP Class won't return to a String

I'm fairly new to PHP so I have a small problem as I'm learning:
I built a Class called DataStrip.php
<?php
final class DataStrip
{
public function DataStrip()
{
// constructor
}
public function stripVars($vars)
{
return $vars;
}
}
?>
and then I'm trying to pass the public function stripVars a value:
<?php
include_once ('lib/php/com/DataStrip.php');
echo($projCat);
$a = new DataStrip;
$a->stripVars($projCat);
echo($a);
?>
however, I get back this error:
( ! ) Catchable fatal error: Object of class DataStrip could not be converted to string in myfilepath
... any advice perhaps on what I could be doing wrong here? Right now this is just a test function as I'm trying to get used to OOP PHP. :)
What do you expect it to happen? You're not saving the result of what stripVars returns into a variable:
$result = $a->stripVars($projCat);
print $result;
What you are trying to do is print the object variable itself. If you want to control what happens when you try to print an object, you need to define the __toString method.
if you want to do that... you need declarate the method __toString()
<?php
final class DataStrip
{
private $vars;
public function DataStrip()
{
// constructor
}
public function stripVars($vars)
{
$this->vars = $vars;
}
public function __toString() {
return (string) $this->vars;
}
}
// then you can do
$a = new DataStrip;
$a->stripVars($projCat);
echo($a);
?>
Shouldn't you return to a variable:
$projCat = $a->stripVars($projCat);
When you echo $a you're echoing the object - not any particular function or variable inside it (since when you declare $a you're declaring it as everything in the class - variables, functions, the whole kit and kaboodle.
I also have issues with php oop, so please correct if I am wrong :)

Categories