I would like to ask, if there is a way, to use variables in a class, that were declared out of it.
Example:
$foo = 'bar';
class foobar{
function example(){
echo "foo{$foo}";
}
}
$foobar = new foobar;
$foobar->example();
This code produces a notice: Notice: Undefined variable: foo
Is there a way to make it work? Or is there some work-around?
You could give this argument to your class with a constructor
class foobar{
private $foo;
public function __construct($name) {
$this->foo = $name;
}
}
and then use it.
Or what PeeHaa means, you could change your method to
function example($param){
echo "foo{$param}";
}
and call it like this
$foobar->example($foo);
Use a construct to import it or use the global keyword. You could do something like this:
$var = 'value';
class foobar {
private $classVar;
function __construct($param) {
$this->classVar = $param;
}
}
And initiate it like this:
$var = 'value';
$inst = new foobar($var);
Or you can use global variables (which I wouldn't recommend in this case) and do something like this:
$var = 'value';
class foobar {
global $var;
function show() {
echo $var;
}
}
UPDATE: To use a class within another class, it may be instantiated in the constructor if its instance is needed throughout implementation, or it may be instantiated only when needed.
To create a reference to another class inside the constructor, do something like this:
class class1 {
private $someVar;
function __construct() {
$this->someVar = 'success';
}
function doStuff() {
return $this->someVar;
}
}
class class2 {
private $ref;
private $val;
function __construct() {
$this->ref = new class1();
$this->val = $this->ref->doStuff();
// $this->val now holds the value 'success'
}
}
$inst = new class2(); // upon calling this, the $val variable holds the value 'success'
Or you can call it only when needed, like so:
class class1 {
private $someVar;
function __construct() {
$this->someVar = 'success';
}
function doStuff() {
return $this->someVar;
}
}
class class2 {
private $ref;
private $val;
function __construct() {
// do something
}
function assign() {
$this->ref = new class1();
$this->val = $this->ref->doStuff();
// $this->val now holds the value 'success'
}
}
$inst = new class2(); // the $val variable holds no value yet
$inst->assign(); // now $val holds 'success';
Hope that helps you.
Yes add
class foobar{
function example(){
global $foo;
echo "foo{$foo}";
}
}
** putting it in another class is better though, or passing it to the method you're using is better too **
Related
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();
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.
How can I access to class variable from outside without creating new instance in PHP ? Something like this:
class foo
{
public $bar;
}
echo foo::$bar;
Is it possible or I must create method that will print or return this value and use it or create new instance ( $a = new foo; echo $a->$bar ) ?
EDIT: I don't want to create constant but classic variable that will be changed later.
make this variable static to access it with out class object.
If you wanted to change static variable value by method then you need to use static method
you can try like this:
class foo
{
public static $bar ="google";
public static function changeVal($val){
self::$bar=$val;
}
}
foo::changeVal("changed :)");
echo foo::$bar;
Output : changed :)
Demo : https://eval.in/107138
You also can changed it like this without static method:
foo::$bar = "changed";
demo : https://eval.in/107139
like this:
class foo
{
public static $bar ="google";
}
echo foo::$bar;
Output: google
demo: https://eval.in/107126
IF it makes sense to use a static variable:
class foo{
public static $bar = 'example';
}
Which could be accessed like so:
echo foo::$bar;
If the value will never change during runtime, then you probably want a class constant (http://www.php.net/oop5.constants)
class foo {
const bar = 'abc';
}
...otherwise you want a public static variable (http://www.php.net/manual/en/language.oop5.static.php)
class foo {
public static $bar = 'abc';
}
...either way, access it like this
echo foo::bar;
You can access the class variable without creating instances only when the variable is markesd as static:
class foo
{
public static $bar;
}
This is how you use a class variable:
// with instantiation
class foo {
// initialize on declare
public $bar = 1;
// or initialize in __construct()
public function __construct(){
$this->bar = 1;
}
}
$foo = new foo();
var_dump($foo->bar);
// static way
class static_foo {
public static $bar = 1;
}
var_dump(static_foo::$bar);
And this is how you instantiate a class from a random class name string variable.
$foo = new foo();
$random_class_name = $foo->bar;
try {
// following line throws if class is not found
$rc = new \ReflectionClass($random_class_name);
$obj = $rc->newInstance();
// can be used with dynamic arguments
// $obj = $rc->newInstance(...);
// $obj = $rc->newInstanceArgs(array(...));
} catch(\Exception $Ex){
$obj = null;
}
if($obj){
// you have a dynamic object
}
What's your actual question?
So say I have the following code,
$obj = new foo();
echo $obj;
class foo {
public function __construct()
{
return 'a';
}
}
How do I make $obj echo the string 'a'?
How do I make $obj refer to or equal what is returned by the object/class?
Need to return a value from a __construct(), and also a normal private function within another class. For example:
$obj2 = new foo2();
echo $obj2;
class foo2 {
public function __construct()
{
bar();
}
private bar()
{
return 'a';
}
}
Thanks!
you can use the magic __toString() method to convert your class to a representing string.
You should not return something in your constructor, __toString() is automaticly called if you try to use your instance as string (in case of echo).
from php.net:
<?php
// 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;
?>
http://www.php.net/manual/en/language.oop5.magic.php#object.tostring
Constructors in PHP are more like initialisation functions; their return value is not used, unlike JavaScript for instance.
If you want to change the way objects are normally echoed you need to provide the magic __toString() method:
class foo
{
private $value;
public function __construct()
{
$this->value = 'a';
}
public function __toString()
{
return $this->value;
}
}
A private method that would return the value can be used in a similar manner:
class foo2
{
private function bar()
{
return 'a';
}
public function __toString()
{
return $this->bar();
}
}
I have a global variable outside my class = $MyNumber;
How do I declare this as a property in myClass?
For every method in my class, this is what I do:
class myClass() {
private function foo() {
$privateNumber = $GLOBALS['MyNumber'];
}
}
I want this
class myClass() {
//What goes here?
var $classNumber = ???//the global $MyNumber;
private function foo() {
$privateNumber = $this->classNumber;
}
}
EDIT: I want to create a variable based on the global $MyNumber but
modified before using it in the methods
something like: var $classNumber = global $MyNumber + 100;
You probably don't really want to be doing this, as it's going to be a nightmare to debug, but it seems to be possible. The key is the part where you assign by reference in the constructor.
$GLOBALS = array(
'MyNumber' => 1
);
class Foo {
protected $glob;
public function __construct() {
global $GLOBALS;
$this->glob =& $GLOBALS;
}
public function getGlob() {
return $this->glob['MyNumber'];
}
}
$f = new Foo;
echo $f->getGlob() . "\n";
$GLOBALS['MyNumber'] = 2;
echo $f->getGlob() . "\n";
The output will be
1
2
which indicates that it's being assigned by reference, not value.
As I said, it will be a nightmare to debug, so you really shouldn't do this. Have a read through the wikipedia article on encapsulation; basically, your object should ideally manage its own data and the methods in which that data is modified; even public properties are generally, IMHO, a bad idea.
Try to avoid globals, instead you can use something like this
class myClass() {
private $myNumber;
public function setNumber($number) {
$this->myNumber = $number;
}
}
Now you can call
$class = new myClass();
$class->setNumber('1234');
Simply use the global keyword.
e.g.:
class myClass() {
private function foo() {
global $MyNumber;
...
$MyNumber will then become accessible (and indeed modifyable) within that method.
However, the use of globals is often frowned upon (they can give off a bad code smell), so you might want to consider using a singleton class to store anything of this nature. (Then again, without knowing more about what you're trying to achieve this might be a very bad idea - a define could well be more useful.)
What I've experienced is that you can't assign your global variable to a class variable directly.
class myClass() {
public $var = $GLOBALS['variable'];
public function func() {
var_dump($this->var);
}
}
With the code right above, you get an error saying "Parse error: syntax error, unexpected '$GLOBALS'"
But if we do something like this,
class myClass() {
public $var = array();
public function __construct() {
$this->var = $GLOBALS['variable'];
}
public function func() {
var_dump($this->var);
}
}
Our code will work fine.
Where we assign a global variable to a class variable must be inside a function. And I've used constructor function for this.
So, you can access your global variable inside the every function of a class just using $this->var;
What about using constructor?
class myClass {
$myNumber = NULL;
public function __construct() {
global myNumber;
$this->myNumber = &myNumber;
}
public function foo() {
echo $this->myNumber;
}
}
Or much better this way (passing the global variable as parameter when inicializin the object - read only)
class myClass {
$myNumber = NULL;
public function __construct($myNumber) {
$this->myNumber = $myNumber;
}
public function foo() {
echo $this->myNumber;
}
}
$instance = new myClass($myNumber);
If you want to access a property from inside a class you should:
private $classNumber = 8;
I found that globals can be used as follows:
Create new class:
class globalObj{
public function glob(){
global $MyNumber;
return $this;
}
}
So, now the global is an object and can be used in the same way:
$this->glob();
class myClass
{
protected $foo;
public function __construct(&$var)
{
$this->foo = &$var;
}
public function foo()
{
return ++$this->foo;
}
}