PHP object (not class) is not available in another class - php

I read that objects (instantiations of classes) are of global scope. This makes sense because objects (again, I am not talking about classes) should be easy to be reused in other parts of the code. But it seems that this information is wrong. Look at this example:
<?php
class test {
public $returnvalue = "foobar";
}
$testobject = new test();
class getvalue {
private $var;
function printvalue() {
$var = $testobject->returnvalue;
print "$var";
}
}
$getvalueobject = new getvalue();
$getvalueobject->printvalue();
?>
This code returns the error:
Trying to get property of non-object in ...
So, what would I have to do to make the $testobject (instantiation of class "test") available in class getvalue?
Thanks in advance.

<?php
class test {
public $returnvalue = "foobar";
}
//$testobject = new test(); MOVE INTO METHOD
class getvalue {
private $var;
function printvalue() {
$testobject = new test(); //For instance here
$var = $testobject->returnvalue;
print "$var";
}
}
$getvalueobject = new getvalue();
$getvalueobject->printvalue();
?>
Here is the documentation: http://php.net/manual/en/language.variables.scope.php

<?php
class test {
public $returnvalue = "foobar";
}
$testobject = new test();
class getvalue {
public $classObject;
function printvalue() {
$var = $this->classObject->returnvalue;
print "$var";
}
}
$getvalueobject = new getvalue();
$getvalueobject->classObject = $testobject;
$getvalueobject->printvalue();
?>
Example with class extend
<?php
class test {
public $returnvalue = "foobar";
}
// If you use extends in PHP classes you can access all variables and methods from the base class (In this example the base class would be Test)
class getvalue extends test {
function printvalue() {
// Because we extended the base class Test, we can access it's public variable returnvalue
$var = $this->returnvalue;
print "$var";
}
}
$getvalueobject = new getvalue();
$getvalueobject->printvalue();
?>

I was wrong. Objects do not have global scope.
So if you need to use an object in another class then you have to pass it either to the __construct function and store the object in the class properties or you have to pass it to the function where it is used:
<?php
class test {
public $returnvalue = "foobar";
}
$testobject = new test();
class getvalue {
private $var;
private $testobject;
function __construct($testobject) {
$this->testobject = $testobject;
}
function printvalue() {
$var = $this->testobject->returnvalue;
print "$var";
}
}
$getvalueobject = new getvalue($testobject);
$getvalueobject->printvalue();
?>
or
<?php
class test {
public $returnvalue = "foobar";
}
$testobject = new test();
class getvalue {
private $var;
function printvalue($testobject) {
$var = $testobject->returnvalue;
print "$var";
}
}
$getvalueobject = new getvalue();
$getvalueobject->printvalue($testobject);
?>

Related

How can I cast class for my object for PHP?

I have object $obj (class A).
Can I convert class for $obj to B?
Perhaps there is another way.
Example:
class A
{
public $AProp = 1;
public function &Convert($ATypeName)
{
// HOW?
return $this;
}
}
class B extends A
{
public $BProp = 2;
}
$obj=new A();
$obj->Convert("B");
print_r($obj->BProp);
I wrote next solution, but it is no good.
(It looks like your post is mostly code; I add some more details)
class A
{
public $AProp = 1;
public function &Convert($ATypeName)
{
$Result = new $ATypeName; // Create new object
$Result->AProp = $this->AProp; // Copy params...
return $Result;
}
}
class B extends A
{
public $BProp = 2;
}
$obj = new A();
$obj->AProp = 3;
$obj = $obj->Convert("B");
print_r($obj);
u are trying to use c++-way of class extending.
the php-way is smth like this:
<?php
class A
{
protected $prop = 1;
public function getProp()
{
return $this->prop;
}
}
class B extends A
{
protected $prop = 2;
}
$obj=new A();
print_r($obj->getProp());
$obj=new B();
print_r($obj->getProp());
also take a look on late static bindings - http://php.net/manual/en/language.oop5.late-static-bindings.php
<?php
class A
{
public static $prop = 1;
public function getProp()
{
return static::$prop;
}
}
class B extends A
{
public static $prop = 2;
}
$obj=new A();
print_r($obj->getProp());
$obj=new B();
print_r($obj->getProp());
This is the only way:
$obj = new B();
Since inheritance is used you can access all class A func and var, like $this->Aprop

Cannot create object in class PHP

I try to create object in PHP class, but i get some interesting errors in IDE, like unexpected ( token etc. Here is my code:
class A {
public $a = 1;
}
class B {
$aa = new A();
}
Where is the problem?
In PHP, you can only assign "fixed" values to properties in the class definition.
class A {
public $a = 3; // will work
public $b = "hello"; // will work
public $c = foo(); // won't work
public $d = new Foo(); // won't work
}
If you want to do so, you can use the __construct() method which will be called every time a new instance is created or any other method that you call.
class B {
public $aa; // define visibility of $aa
function __construct() {
$this->aa = new A();
}
}
You need to make a constructor on class A
class A {
function __construct() {
$this->a = 1;
}
public function returnA() {
return $this->a;
}
}
$aa = new A();
echo $aa->returnA();
Try to create a constructor in class A and see if it works:
class A {
public $a;
function __construct()
{
$this->$a = 1;
}
}
class B {
$aa = new A();
}

get a list of all variables defined outside a class by user

i have something like this:
class foo
{
//code
}
$var = new foo();
$var->newVariable = 1; // create foo->newVariable
$var->otherVariable = "hello, im a variable"; //create foo->otherVariable
i can get in class foo a list of all variables defined outside by user (newVariable, otherVariable,etc)? Like this:
class foo
{
public function getUserDefined()
{
// code
}
}
$var = new foo();
$var->newVariable = 1; // create foo->newVariable
$var->otherVariable = "hello, im a variable"; //create foo->otherVariable
var_dump($var->getUserDefined()); // returns array ("newVariable","otherVariable");
Thanks!.
Yes, using get_object_vars() and get_class_vars():
class A {
var $hello = 'world';
}
$a = new A();
$a->another = 'variable';
echo var_dump(get_object_vars($a));
echo '<hr />';
// Then, you can strip off default properties using get_class_vars('A');
$b = get_object_vars($a);
$c = get_class_vars('A');
foreach ($b as $key => $value) {
if (!array_key_exists($key,$c)) echo $key . ' => ' . $value . '<br />';
}
What is your goal? Imo it's not very good practice (unless you really know what you are doing). Maybe it's good idea consider create some class property like "$parameters" and then create setter and getter for this and use it in this way:
class foo {
private $variables;
public function addVariable($key, $value) {
$this->variables[$key] = $value;
}
public function getVariable($key) {
return $this->variables[$key];
}
public function hasVariable($key) {
return isset($this->variables[$key]);
}
(...)
}
$var = new foo();
$var->addVariable('newVariable', 1);
$var->addVariable('otherVariable', "hello, im a variable");
And then you can use it whatever you want, for example get defined variable:
$var->getVariable('otherVariable');
To check if some var is already defined:
$var->hasVariable('someVariable')
get_class_vars() http://php.net/manual/en/function.get-class-vars.php
You question is not clear though.
$var->newVariable = 1;
there are two possible contex of above expression
1) you are accessing class public variables.
like
class foo
{
public $foo;
public function method()
{
//code
}
}
$obj_foo = new foo();
$obj_foo->foo = 'class variable';
OR
2) you are defining class variable runtime using _get and _set
class foo
{
public $foo;
public $array = array();
public function method()
{
//code
}
public function __get()
{
//some code
}
public function __set()
{
// some code
}
}
$obj_foo = new foo();
$obj_foo->bar= 'define class variable outside the class';
so in which context your question is talking about?

shared variable across multiple class instances that I can change outside the class

the code explains it better:
class Class{
$var = 0;
function getvar()
echo $this->var;
}
}
$inst1 = new Class();
// I want to change $var here to 5
$inst2 = new Class();
echo $inst2->getvar(); // should be 5
Is it possible
Static. http://php.net/manual/en/language.oop5.static.php
class MyClass {
public static $var = 0;
function setVar($value) {
self::$var = $value;
}
function getVar() {
return self::$var;
}
}
echo MyClass::$var;
MyClass::setVar(1);
echo MyClass::getVar(); //Outputs 1
You should be able to do this using a static member variable.
class foo {
private static $var;
public static setVar($value) {
self::$var = $value;
}
public static getVar() {
return self::$var;
}
}
$a = new foo;
$a::setVar('bar');
$b = new foo;
echo $b::getVar();
// should echo 'bar';
You should declare $var to be static:
A data member that is commonly
available to all objects of a class is
called a static member. Unlike regular
data members, static members share the
memory space between all objects of
the same class.
You can use static variables:
class AAA{
public static $var = 0;
function getvar() {
return AAA::$var;
}
}
AAA::$var = "test";
$a1 = new AAA();
var_dump($a1->getvar());
var_dump(AAA::$var);

How can I define a variable before create the class?

How can I define a variable before or while initializing the class?
<?php
class class{
public $var;
public function __construct(){
echo $this -> var;
}
}
$class = new class;
$class -> var = "var";
?>
If you mean instantiating the class, then use the constructor:
class Foo {
private $_bar;
public function __construct($value) {
$this->_bar = $value;
}
}
$test = new Foo('Mark');
You can do it 2 ways - see this example:
class bla {
public static $yourVar;
public function __construct($var) {
self::yourVar = $var
}
}
// you can set it like this without instantiating the class
bla::$yourVar = "lala";
// or pass it to the constructor while it's instantiating
$b = new bla("lala");
The first part you can only do with a static, but if you don't want to use a static, you'll have to initialize it via the constructor.
Hope that's what you were looking for...
$myVariable; // variable is defined
$myVariable = new myClass(); // instance of a class
class myClass {
protected $theVariable;
protected function myClass($value) {
$this->$theVariable = $value;
}
}
$theVariable = 'The Value';
$theClass = new myClass($theVariable);
echo $theClass->theVariable;

Categories