How to echo a parameter from a class using PHP? - php

I want $foo->display(); to display Hello World
Here is what I tried:
class MyAttribute
{
public function init($var)
{
$this->setString($var);
}
public function display()
{
$this->setString = $var;
}
}
$foo = new MyAttribute("Hello World");
$foo->display();

You need to use the return keyword to pass the variable back, however that is not your issue, consider the following:
class MyAttribute {
private $attr;
public function __construct($attr)
{
$this->attr = $attr;
}
public function get_attr()
{
return $this->attr;
}
}
$attr = new MyAttribute('Hello World');
echo $attr->get_attr();
The constructor executes first when the class is instantiated and we set the property $attr with the variable that is passed to said constructor.
In the get_attr functionm the important part to notice is the return keyword which I have linked you to the documentation for it above.
You don't necessarily need a constructor, you can add another function called set_attr which sets/changes the value of $attr but seeing as you are using the constructor in your original code, I've left it in.
Live Example
Repl
Reading Material
PHP OOP

You Can use __construct because PHP will automatically call the __construct() method/function when you create an object from your class.
we can provide a value for the $par property when we create our MyAttribute objects.
class MyAttribute
{
private $var;
public function __construct($var)
{
$this->var = $var;
}
public function display()
{
return $this->var;
}
}
$foo = new MyAttribute("Hello World");
echo $foo->display();

Related

Nested method in php object

How can I create something like
MyObject->property->method()
in PHP?
I only know how to create a method for a class:
class MyObject
{
public function MyMethod()
{
// do something
}
}
In Javascript I can easily do something like
var MyObject = {
property : {
method : function ()
{
// do something
}
}
}
How do I do that?
In Javascript you can create objects and methods inline, in PHP you need to have a class and instantiate it:
class Foo {
public function method() {}
}
class MyObject {
public $property;
public function __construct() {
$this->property = new Foo;
}
}
$o = new MyObject;
$o->property->method();
You can set an object as the value of a property. Something like this:
class Foo {
public $Bar;
public function __construct() {
$this->Bar = new Bar();
}
}
class Bar {
public function ShowBar() {
echo 'Bar';
}
}
$Foo = new Foo();
$Foor->Bar->ShowBar();
As others have correctly answered, this works differently in PHP and Javascript. And these differences are also the reason why in PHP you need to define the class methods before you run them. It might become a bit more dynamic in the future but I'm sure not on the level of Javascript.
You can however fake this a bit in PHP because you can assign functions to properties dynamically:
$myObject = new PropCall;
$myObject->property->method = function() {
echo "hello world\n";
};
$myObject->property->method();
This example outputs:
hello world
This does work because some little magic has been added in the instantiated object:
class PropCall
{
public function __call($name, $args) {
if (!isset($this->$name)) {
return null; // or error handle
}
return call_user_func_array($this->$name, $args);
}
public function __get($name) {
$this->$name = new PropCall;
return $this->$name;
}
}
This class code checks if a dynamic property has been added with the name of the method called - and then just calls the property as a function.

call_user_func() expects parameter 1 to be a valid callback

I'm just playing around with the call_user_func function in PHP and am getting this error when running this simple code:
<?php
class A
{
public $var;
private function printHi()
{
echo "Hello";
}
public function __construct($string)
{
$this->var = $string;
}
public function foo()
{
call_user_func($this->var);
}
}
$a = new A('printHi');
$a->foo();
?>
I know that if I make a function outside the class called printHi, it works fine, but I'm referring to the class's print hi and not sure why the "this" isn't being registered.
$this->var is evaluating to printHi in your example. However, when you are calling a method of a class, you need to pass the callback as an array where the first element is the object instance and the second element is the function name:
call_user_func(array($this, $this->var));
Here is the documentation on valid callbacks: http://www.php.net/manual/en/language.types.callable.php
Alternatively to Omar's answer, you can also make printHi() a class static function, so you then can call it from call_user_func('A::printHi') , like this:
class A
{
public $var;
public static function printHi()
{
echo "Hello";
}
public function __construct($string)
{
$this->var = $string;
}
public function foo()
{
call_user_func($this->var);
}
}
$a = new A('A::printHi');
$a->foo();
See live example

PHP Assigning a default Function to a class

Im relatively new to PHP but have realized it is a powerfull tool.
So excuse my ignorance here.
I want to create a set of objects with default functions.
So rather than calling a function in the class we can just output the class/object variable and it could execute the default function i.e toString() method.
The Question:
Is there a way of defining a default function in a class ?
Example
class String {
public function __construct() { }
//This I want to be the default function
public function toString() { }
}
Usage
$str = new String(...);
print($str); //executes toString()
There is no such thing as a default function but there are magic methods for classes which can be triggered automatically in certain circumstances. In your case you are looking for __toString()
http://php.net/manual/en/language.oop5.magic.php
Example from Manual:
// Declare a simple class
class TestClass
{
public $foo;
public function __construct($foo)
{
$this->foo = $foo;
}
public function __toString()
{
return $this->foo;
}
}
$class = new TestClass('Hello');
echo $class;
?>
__toString() is called when you print your object, i.e. echo $str.
__call() is the default method for any class.
Either put the toString function code inside __construct, or point to toString.
class String {
public function __construct( $str ) { return $this->toString( $str ); }
//This I want to be the default function
public function toString( $str ) { return (str)$str; }
}
print new String('test');

How can I declare a property inside a method?

I'm a totally newbie in class writing in PHP, started a couple days ago.
I'd like to declare a new "public property" inside a method to be used in other methods.
This is what I thought (Of course it doesnt' work!):
class hello {
public function b() {
public $c = 20; //I'd like to make $c usable by the method output()
}
public function output() {
echo $c;
}
}
$new = new hello;
$new->output();
Thanks in advance for any tips.
I'd like to declare a new "public property" inside a method to be used in other methods.
If the other methods are part of the same class, you don't need a public property, a private property will fit your needs. Private properties are accessible within the same class only which helps to keep things simple.
Also understand the difference between declaring a property and assigning a value to it. Declaring is done when the code is loaded, assigning when it executes. So declaring (or defining) a property (private or public) needs a special place in the PHP syntax, that is in the body of your class and not inside in a function.
You access properties inside the class by using the special variable $this in PHP.
The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs [to]). From PHP Manual
Private property example:
class hello {
private $c; # properties defined like this have the value NULL by default
public function b() {
$this->c = 20; # assign the value 20 to private property $c
}
public function output() {
echo $this->c; # access private property $c
}
}
$new = new hello;
$new->output(); # NULL
$new->b();
$new->output(); # 20
Hope this is helpful. You use a private property because everything else in your program does not need to care about it, so inside your class you know that nothing else can manipulate the value. See as well Visibility­Docs.
Every variable of the class is public when you define it inside of a method (function)! You can do this the following way:
class hello {
public function b() {
$this->c = 20;
}
public function output() {
echo $this->c;
}
}
$new = new hello;
$new->output();
or let function b() return $c and then pass it as a variable to output():
class hello {
public function b() {
return $c = 20;
}
public function output($c) {
echo $c;
}
}
$new = new hello;
$c = $new->b();
$new->output($c);
Remember all variables inside a function are ONLY accessable from within that particular function...unless you use $this of course, which makes the variable a class property!
Also, it's recommended to only return variables...echo is only for the real output, the pure HTML, the template, your view, if you know what I mean :)
Try this instead:
class hello {
public $c = null;
public function b() {
$this->c = 20; //I'd like to make $c usable by the method output()
}
public function output() {
echo $this->c;
}
}
class hello {
public $c;
public function b() {
$this->c = 20;
}
public function output() {
$this->c;
}
}
Note: If you need to use a property in another method you don't need to declare that method as public, you should declare the property as private, and you'll have access to your property with no problem:
class hello {
private $c;
public function b() {
$this->c = 20;
}
public function output() {
$this->c;
}
}
class hello {
public $c;
public function b() {
$this->c = 20; //I'd like to make $c usable by the method output()
}
public function output() {
return $this->c;
}
}
$new = new hello;
echo $new->output();
class hello {
var $c;
function __construct() { // __construct is called when creating a new instance
$this->c = 20;
}
public function getC() {
return $this->c;
// beter to return a value this way you can later decide what to do with the value without modifying the class
}
}
$new = new hello; // create new instance and thus call __construct().
echo $new->getC(); // echo the value
Rewrite this code like this :-
class hello {
public $c;
public function b() {
public $this->c = 20; //I'd like to make $c usable by the method output()
}
public function output() {
echo $this->c;
}
}
$new = new hello;
$new->output();

In PHP: How to call a $variable inside one function that was defined previously inside another function?

I'm just starting with Object Oriented PHP and I have the following issue:
I have a class that contains a function that contains a certain script. I need to call a variable located in that script within another function further down the same class.
For example:
class helloWorld {
function sayHello() {
echo "Hello";
$var = "World";
}
function sayWorld() {
echo $var;
}
}
in the above example I want to call $var which is a variable that was defined inside a previous function. This doesn't work though, so how can I do this?
you should create the var in the class, not in the function, because when the function end the variable will be unset (due to function termination)...
class helloWorld {
private $var;
function sayHello() {
echo "Hello";
$this->var = "World";
}
function sayWorld() {
echo $this->var;
}
}
?>
If you declare the Variable as public, it's accessible directly by all the others classes, whereas if you declare the variable as private, it's accessible only in the same class..
<?php
Class First {
private $a;
public $b;
public function create(){
$this->a=1; //no problem
$thia->b=2; //no problem
}
public function geta(){
return $this->a;
}
private function getb(){
return $this->b;
}
}
Class Second{
function test(){
$a=new First; //create object $a that is a First Class.
$a->create(); // call the public function create..
echo $a->b; //ok in the class the var is public and it's accessible by everywhere
echo $a->a; //problem in hte class the var is private
echo $a->geta(); //ok the A value from class is get through the public function, the value $a in the class is not dicrectly accessible
echo $a->getb(); //error the getb function is private and it's accessible only from inside the class
}
}
?>
Make $var a class variable:
class HelloWorld {
var $var;
function sayHello() {
echo "Hello";
$this->var = "World";
}
function sayWorld() {
echo $this->var;
}
}
I would avoid making it a global, unless a lot of other code needs to access it; if it's just something that's to be used within the same class, then that's the perfect candidate for a class member.
If your sayHello() method was subsequently calling sayWorld(), then an alternative would be to pass the argument to that method.

Categories