This question already has answers here:
How to echo a custom object in PHP?
(4 answers)
Closed 5 years ago.
If you look at the usage for this library,
https://github.com/Gregwar/Formidable
You have,
$form = new Gregwar\Formidable\Form('forms/example.html');
$form->handle(function() {
echo "Form OK!";
}, function($errors) {
echo "Errors: <br/>";
foreach ($errors as $error) {
echo "$error<br />";
}
});
echo $form;
My question is, how is this done?
How do you echo the $form object..
for eg if I have
class Something
{
public $somevariable = 'London';
public function __construct()
{
$this->foo();
}
public function foo(){
//Do Something
}
}
$myObj = new Something();
echo $myObj;
The above code gives me an error.
What can I do to echo $myObj and not get an error so I can have something displayed on the screen?
We all know we can do something like,
echo $myObj->somevariable;
without an error.. How can I do
echo $myObj;
without getting an error as it is done in the Formidable library.
Magic method __toString() in your class. This allows your class to execute the code in that method when your object is treated like a string (i.e. when used with echo). The method must return a string, otherwise it will raise an error.
You will notice in the library you linked, that they have one in their form class.
/**
* Convert to HTML
*/
public function __toString()
{
return $this->getHtml();
}
You can add __tostring() magic function to your class
class Something
{
public $somevariable = 'London';
public function __construct()
{
$this->foo();
}
public function foo(){
//Do Something
}
public function __tostring(){
return $this->somevariable;
}
}
Calling echo $myObj will print London
Related
By using the following class:
class SafeGuardInput{
public $form;
public function __construct($form)
{
$this->form=$form;
$trimmed=trim($form);
$specialchar=htmlspecialchars($trimmed);
$finaloutput=stripslashes($specialchar);
echo $finaloutput;
}
public function __destruct()
{
unset($finaloutput);
}
}
and Calling the function, by the following code, it works fine.
<?php
require('source/class.php');
$target="<script></script><br/>";
$forminput=new SafeGuardInput($target);
?>
But if in the SafeGuardInput class if I replace echo $finaloutput; with return $finaloutput; and then echo $forminput; on the index.php page. It DOES NOT WORK. Please provide a solution.
You can't return anything from a constructor. The new keyword always causes the newly created object to be assigned to the variable on the left side of the statement. So the variable you've used is already taken. Once you remember that, you quickly realise there is nowhere to put anything else that would be returned from the constructor!
A valid approach would be to write a function which will output the data when requested:
class SafeGuardInput{
public $form;
public function __construct($form)
{
$this->form=$form;
}
public function getFinalOutput()
{
$trimmed = trim($this->form);
$specialchar = htmlspecialchars($trimmed);
$finaloutput = stripslashes($specialchar);
return $finaloutput;
}
}
Then you can call it like in the normal way like this:
$obj = new SafeGuardInput($target);
echo $obj->getFinalOutput();
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);
?>
Consider this class arrangement - and in particular the magic function __invoke:
class Barman {
public function __construct() {
// .. .constructor stuff - whatever
}
public function makeDrink() {
return "vodka martini, shaken";
}
}
class Bar {
private $arr_barmen = array();
public function __construct() {
$this->arr_barmen['john'] = new Barman();
}
public function __invoke($barman_id) {
echo "I have been invoked";
return $this->arr_barmen[$barman_id];
}
public function aBarFunc($param) {
return "yes it worked ," .$param;
}
}
class Foo {
public $myBar;
public function __construct() {
$this->myBar = new Bar();
}
}
I want to write syntax like this
$company = new Foo();
$company->myBar('john')->makeDrink();
Preferred result:
"vodka martini, shaken"
Actual result:
"Call to undefined method Foo::myBar()"
Invoking myBar() with the magic method should return a barman Object upon which you can call any of the barman's public methods
But now consider this (which does work)
$company = new Foo();
$myBar = $company->myBar;
$drink = $myBar('john')->makeDrink();
echo $drink;
// Result:
// I have been invoked
// vodka martini, shaken
So what's going on? I don't like that workaround - it's not sleek.
I need it to work this way:
$company->myBar('john')->makeDrink();
Please help? :-)
I believe you can just add braces around it:
$company = new Foo();
$drink = ($company->myBar)('john')->makeDrink();
echo $drink; // vodka martini, shaken
This is being caused by an ambiguity in the call you're trying to make:
$company->myBar('john')->makeDrink();
Because myBar is a property, the PHP interpreter isn't expecting it to be callable. It is parsing it as an attempt to call a method called myBar() which doesn't exist, and is thus throwing the error.
The direct way to resolve this is to clarify the ambiguity for the interpreter. You do this by adding curly braces around the property, as follows:
$company->{myBar}('john')->makeDrink();
The code is now explicit that myBar is a property and should be accessed as such, but that it contains a value that is callable and that you wish to make that call.
This whole topic is complicated (slightly) by the fact that PHP 5.x and PHP 7.x behave differently with regard to how they default to handling these kinds of ambiguity. PHP 7 changed the defaults in order to correct some internal inconsistencies within the language. The result is that in situations like this where you have an ambiguity, if you want your code to work across both PHP 5.x and 7.x, you should always use the braces to explicitly define how you want it to work, regardless of whether your code works for you without them.
There is some documentation about this change in the PHP 7.0 upgrade notes, although the examples given don't cover your exact situation.
To attain chaining you have to return the Barman object in invoke.
class Barman {
public function __construct() {
// .. .constructor stuff - whatever
}
public function makeDrink() {
return "vodka martini, shaken";
}
}
class Bar {
private $arr_barmen = array();
public function __construct() {
$this->arr_barmen['john'] = new Barman();
}
public function __invoke($barman_id) {
echo "I have been invoked";
return $this->arr_barmen[$barman_id] = new Barman();
}
public function aBarFunc($param) {
return "yes it worked ," . $param;
}
}
class Foo {
public $myBar;
public function __construct() {
$this->myBar = new Bar();
}
// create a function with variable name to invoke the object
public function myBar($name) {
$mybar = $this->myBar;
return $mybar($name);
}
}
Thank you for the responses. I devised a cute workaround as follows:
class Barman {
public function __construct() {
}
public function makeDrink() {
return "vodka martini, shaken";
}
}
class Bar {
private $arr_barmen = array();
public function __construct() {
$this->arr_barmen['john'] = new Barman();
}
public function getBarman($barman_id) {
return $this->arr_barmen[$barman_id];
}
public function __invoke($barman_id) {
echo "I have been invoked \n";
return $this->arr_barmen[$barman_id];
}
}
class Foo {
private $_myBar;
public function __construct() {
$this->_myBar = new Bar();
}
// The fix
public function myBar($barman_id) {
return $this->_myBar->getBarman($barman_id);
}
}
Usage:
$company = new Foo();
$drink = $company->myBar('john')->makeDrink();
echo $drink; // vodka martini, shaken
How it works?
Foo->myBar becomes private (Foo->$_myBar);
we create a public function with the name myBar inside Foo;
we create a "getBarman" fuction inside Bar which is called from Foo->myBar('john')
A few more steps - and now there's no ambiguity - Foo->myBar() IS always a function.
Cheers
M
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I tried to make a function inside a function:
<?php
class usermanager extends datamanager {
public $id;
public $name;
public $from;
public $twitter;
public $instagram;
public $skype;
public $regIP;
public $lastIP;
public $email;
public function __construct($exists = false,$uid = 0) {
if ($exists == true) {
$this->id = $uid;
$this->name = $this->fetch("SELECT * FROM users WHERE ID = '".$uid."';")->name;
public function getProfile() {
profile();
}
}
else {
public function new($name,$password,$email) {
$this->autocommit(false);
if (!($do = $this->query("INSERT INTO users (name,password,email,rank) VALUES ('".$name."',PASSWORD('".$password."'),'".$email."','0');"))) {
$this->rollback();
return false;
}
else {
$this->commit();
return true;
}
} //end new()
} //end else
} //end __construct()
public function __set() {
trigger_error("Can not edit read-only variable",E_USER_ERROR);
} //end __set()
private function profile() {
$gets = array("twitter","instagram","skype","from");
$fetch = $this->fetch("SELECT * FROM users WHERE ID = '".$this->id."';");
foreach ($gets as $get) {
$this->$get = $fetch->$get;
}
}
} //end class
?>
Because I saw this I thought it would work, but I got:
Parse error: syntax error, unexpected T_PUBLIC in /home/a7405987/usermanager.php on line 21
Why doesn't this work?
It is fixed now, but now I'm getting another error:
Call to undefined function getProfile()
How can I fix this?
Defining a function within a function isn't a great idea. Aside from classes, any function definitions are automatically global. The public and private keywords are only valid in a class definition, not within a class function. If you were to remove the public from your inner function definition, it would run without error, but the result would be a globally defined getProfile().
This example should help demonstate the issue:
<?php
class Test {
public function foo() {
function bar() {
echo "Hello from bar!" . PHP_EOL;
}
echo "Hello from foo!" . PHP_EOL;
}
}
$t = new Test;
// PHP Fatal error: Call to undefined method Test::bar()
// $t->bar();
// Works, prints "Hello from foo!"
// bar() is now defined, but not where you expect
$t->foo();
// PHP Fatal error: Call to undefined method Test::bar()
// $t->bar();
// Works, prints "Hello from bar!"
// Note that this is global scope, not from Test
bar();
Demo in action
You cannot use modifiers public/private/protected inside a member function or here a constructor. You can however declare a function inside a method :
public function classMember() {
function doSomething() {
//do something
}
doSomething()
}
For your particular problem, you should instanciate your class and then check if it exists, otherwise insert it.
You cannot change the structure of a class depending on the context it is called
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP method chaining?
I occasionally see some php applications use classes like that:
$Obj = new Obj();
$Obj->selectFile('datafile.ext')->getDATA();
The example above gets the contents of the selected file then returns them ( just an example );
Well, before i decided to ask you how can I do this, I tried this:
class Someclass {
public function selectFile( $filename ) {
$callAclass = new AnotherClass( $filename );
return $callAclass;
}
// Other functions ...
}
class AnotherClass {
protected $file_name;
public function __construct ( $filename ) { $this->file_name = $filename; }
public function getDATA ( ) {
$data = file_get_contents( $this->file_name );
return $data;
}
// funcs , funcs, funcs ....
}
Is that the right way to accomplish this task? And please tell me what these classes are called.
It's called method chaining. Have a look at this question on SO.
Here's a way you can do what you're trying to achieve:
class File
{
protected $_fileName;
public function selectFile($filename)
{
$this->_fileName = $filename;
return $this;
}
public function getData()
{
return file_get_contents($this->_fileName);
}
}
$file = new File();
echo $file->selectFile('hello.txt')->getData();
Notice we return $this in the selectFile, this enables us to chain another method onto it.
The above example (the first one) is something called chaining. Here's a regular class:
class a_class
{
public function method_a()
{
echo 'method a';
}
public function method_b()
{
echo ' - method b';
}
}
You'd call those like this:
$class = new a_class();
$class->method_a();
$class->method_b();
Which would echo 'method a - method b'. Now to chain them, you'd return the object in the methods:
class a_class
{
public function method_a()
{
echo 'method a';
return $this;
}
public function method_b()
{
echo ' - method b';
return $this;
}
}
You'd call those like this:
$class = new a_class();
$class->method_a()->method_b();
Which would also echo 'method a - method b'.
Although I have returned the object in the last method - you strictly wouldn't need to, only the preceding methods require that for chaining.