Php Include properties within class - php

I'm having an issue calling a variable thats included in a class. What am I missing here? Thank you in advance for the support. Very much appreciated.
//index2.php
$var2 = 'var2';
//index.php
class something {
__construct() {
include('index2.php');
}
}
$run_it = new something();
echo $run_it->var2; //how do I call var2?

You could do this. Kind of a strange way to do things but here goes:
index.php
<?php
class something{
function __construct() {
include('index2.php');
}
}
//s1
$s1 = new something();
$s1->var2 = 'var2 changed';
//s2
$s2 = new something();
//print em out
print_r($s1);
print_r($s2);
index2.php
<?php
$this->var2 = 'var2'; //$this pseudo-variable works because we're including index2.php within the scope of our class instance
?>
Output
$ php a.php
something Object
(
[var2] => var2 changed
)
something Object
(
[var2] => var2
)

You cannot extend property's of a class with including files. The class is defined as it is written. You have the following ways to add code to a class dynamically.
Extend a class.
Use traits (copy pasting functions into a class)
Use magic methods (__call, __get, __set)
This example will print variables defined in the global scope (like your example) as you wanted it to do.
However, this is not the way it should be used and I suggest finding a different method of writing your class.
include 'somefile.php'; // <?php $var3 = 'testing' ?>
class foo{
public $var2 = 'var2'; # should be declared within the class.
public function __get($name){
// property 'var3' is not defined in the class so this method is magically called instead.
if(isset($GLOBALS[$name])){
return $GLOBALS[$name]; // Here we return the value $var3 defined in the global scope.
} else {
trigger_error("Call to undefined variable '$name'");
}
}
public function __construct(){ # Missed function statement.
echo 'hello';
}
}
$c = new foo();
echo $c->var3; // testing

If your index2.php contains this:
$var2 = 'var2';
Then you can include that file to get access to $var2. You can then pass that variable to your something constructor as an argument:
//index.php
class something {
public $var2;
public function __construct($arg) {
$this->var2 = $arg;
}
}
include 'index2.php';
$run_it = new something($var2);
echo $run_it->var2; // echos 'var2'
It's obvious there are other ways to do something like what you're attempting to do (there is usually more than one way to do most things), but really the most sensible way to get external data into your object is to pass it via constructor arguments.
If you don't do this, the class will forever depend on some other file existing in the correct location relative to the class or calling file, with all of the correct variables set in it. If that file is altered or moved, objects of that class may not function properly if they can even be instantiated at all.

I agree with Xorifelse, you can do it with traits. example.
fields.php
trait Aa {
public $fields = [
"name"=>"string->5",
"number"=>"integer->3",
];
}
traits.php
include('fields.php');
class ABC {
use Aa;
public function __set($field,$value)
{
if(array_key_exists($field,$this->fields))
{
$this->fields[$field] = $value;
}
else
{
$this->fields[$field] = null;
}
}
public function __get($field)
{
if(array_key_exists($field,$this->fields))
{
return $this->fields[$field];
}
else
{
return null;
}
}
}
$a = new ABC();
$a->number = 111;
var_dump($a->fields);
array(2) {
["name"]=>
string(9) "string->5"
["number"]=>
int(111)
}
var_dump($a->number);
int(111)

You can take advantage of get_defined_vars. Assuming your variables are in a file (e.g. filevars.php):
filevars.php
<?php
$name = 'myName';
$address = 'myAddress';
$country = 'myCountry';
$phones = array('123456789','987654321');
?>
You can add a method to your class (getVars) and define a property (vars) that wraps all variables existing in filevars.php:
class-test.php
<?php
class Test
{
public $vars;
function getVars()
{
include ('filevars.php');
$this->vars = get_defined_vars();
}
}
?>
Usage
<?php
include ('class-test.php');
$myClass = new Test();
$myClass->getVars();
print_r($myClass->vars);
?>
Output:
Array
{
[name] => myName
[address] => myAddress
[country] => myCountry
[phones] => Array
{
[0] => 123456789
[1] => 987654321
}
}
You can also refer any individual included variable, e.g.:
echo $myClass->vars['country']; // myCountry

Related

How do I get the included elements during include in php?

I'd like to get the class/included variables/elements when I included a php file/class, somehow maybe I should try reflection to do that? If so, how?
For instance, I'd have a PHP class called foo.php:
<?php
class foo
{
public function bar()
{
return "foobar";
}
}
?>
then, in bar.php, I would like to:
<?php
class bar
{
public function foo()
{
$included_resources = include("foo.php"); // Notice, $included_resources is an array
if (($key = array_search("foo", $included_resources)) != false) // "foo" can be any variable or class name
return $included_resources[$key]->bar();
}
}
$helloworld = new bar();
echo $helloworld->foo();
?>
Result: a string value of "foobar" will be represented on the screen
First, store the declared variables in an array before including a file. Then do the include. Then store the declared variables in another array again. Then simply check the difference:
$declared_vars_before = get_defined_vars();
include 'another_file.php';
$declared_vars_after = get_defined_vars();
foreach ($declared_vars_after as $value) {
if (!in_array($value, $defined_vars_before)) {
echo $value . '<br>';
}
}
Same with classes, but use get_declared_classes instead of get_defined_vars.

Can you define class variables from within a class method in PHP?

I want to pull all info about a file from a files table, but that table's structure might change.
So, I'd like to pull all the field names from the table and use them to generate the class variables that contain the information, then store the selected data to them.
Is this possible?
Yes you can, see php overloading.
http://php.net/manual/en/language.oop5.overloading.php
Quick Example: ( Not this isn't great usage )
<?php
class MyClass{
var $my_vars;
function __set($key,$value){
$this->my_vars[$key] = $value;
}
function __get($key){
return $this->my_vars[$key];
}
}
$x = new MyClass();
$x->test = 10;
echo $x->test;
?>
Sample
<?php
class TestClass
{
public $Property1;
public function Method1()
{
$this->Property1 = '1';
$this->Property2 = '2';
}
}
$t = new TestClass();
$t->Method1();
print( '<pre>' );
print_r( $t );
print( '</pre>' );
?>
Output
TestClass Object
(
[Property1] => 1
[Property2] => 2
)
As you can see, a property that wasn't defined was created just by assigning to it using a reference to $this. So yes, you can define class variable from within a class method.

Get a static property of an instance

If I have an instance in PHP, what's the easiest way to get to a static property ('class variable') of that instance ?
This
$classvars=get_class_vars(get_class($thing));
$property=$classvars['property'];
Sound really overdone. I would expect
$thing::property
or
$thing->property
EDIT: this is an old question. There are more obvious ways to do this in newer
PHP, search below.
You need to lookup the class name first:
$class = get_class($thing);
$class::$property
$property must be defined as static and public of course.
From inside a class instance you can simply use self::...
class Person {
public static $name = 'Joe';
public function iam() {
echo 'My name is ' . self::$name;
}
}
$me = new Person();
$me->iam(); // displays "My name is Joe"
If you'd rather not
$class = get_class($instance);
$var = $class::$staticvar;
because you find its two lines too long, you have other options available:
1. Write a getter
<?php
class C {
static $staticvar = "STATIC";
function getTheStaticVar() {
return self::$staticvar;
}
}
$instance = new C();
echo $instance->getTheStaticVar();
Simple and elegant, but you'd have to write a getter for every static variable you're accessing.
2. Write a universal static-getter
<?php
class C {
static $staticvar = "STATIC";
function getStatic($staticname) {
return self::$$staticname;
}
}
$instance = new C();
echo $instance->getStatic('staticvar');
This will let you access any static, though it's still a bit long-winded.
3. Write a magic method
class C {
static $staticvar = "STATIC";
function __get($staticname) {
return self::$$staticname;
}
}
$instance = new C();
echo $instance->staticvar;
This one allows you instanced access to any static variable as if it were a local variable of the object, but it may be considered an unholy abomination.
classname::property;
I think that's it.
You access them using the double colon (or the T_PAAMAYIM_NEKUDOTAYIM token if you prefer)
class X {
public static $var = 13;
}
echo X::$var;
Variable variables are supported here, too:
$class = 'X';
echo $class::$var;
You should understand what the static property means. Static property or method is not for the objects. They are directly used by the class.
you can access them by
Class_name::static_property_name
These days, there is a pretty simple, clean way to do this.
<?php
namespace Foo;
class Bar
{
public static $baz=1;
//...
public function __toString()
{
return self::class;
}
}
echo Bar::$baz; // returns 1
$bar = new Bar();
echo $bar::$baz; // returns 1
You can also do this with a property in PHP 7.
<?php
namespace Foo;
class Bar
{
public static $baz=1;
public $class=self::class;
//...
}
$bar = new Bar();
echo $bar->class::$baz; // returns 1
class testClass {
public static $property = "property value";
public static $property2 = "property value 2";
}
echo testClass::$property;
echo testClass::property2;

Reset Class Instance Variables via Method

Does anyone know how to reset the instance variables via a class method. Something like this:
class someClass
{
var $var1 = '';
var $var2 = TRUE;
function someMethod()
{
[...]
// this method will alter the class variables
}
function reset()
{
// is it possible to reset all class variables from here?
}
}
$test = new someClass();
$test->someMethod();
echo $test->var1;
$test->reset();
$test->someMethod();
I know I could simply do $test2 = new SomeClass() BUT I am particularly looking for a way to reset the instance (and its variables) via a method.
Is that possible at all???
You can use reflection to achieve this, for instance using get_class_vars:
foreach (get_class_vars(get_class($this)) as $name => $default)
$this -> $name = $default;
This is not entirely robust, it breaks on non-public variables (which get_class_vars does not read) and it will not touch base class variables.
Yes, you could write reset() like:
function reset()
{
$this->var1 = array();
$this->var2 = TRUE;
}
You want to be careful because calling new someClass() will get you an entirely new instance of the class completely unrelated to the original.
this could be easy done;
public function reset()
{
unset($this);
}
Sure, the method itself could assign explicit values to the properties.
public function reset()
{
$this->someString = "original";
$this->someInteger = 0;
}
$this->SetInitialState() from Constructor
Just as another idea, you could have a method that sets the default values itself, and is called from within the constructor. You could then call it at any point later as well.
<?php
class MyClass {
private $var;
function __construct() { $this->setInitialState(); }
function setInitialState() { $this->var = "Hello World"; }
function changeVar($val) { $this->var = $val; }
function showVar() { print $this->var; }
}
$myObj = new MyClass();
$myObj->showVar(); // Show default value
$myObj->changeVar("New Value"); // Changes value
$myObj->showVar(); // Shows new value
$myObj->setInitialState(); // Restores default value
$myObj->showVar(); // Shows restored value
?>

Simple PHP classes question

So I have:
class foo {
public $variable_one;
public $variable_two;
function_A(){
// Do something
$variable_one;
$variable_two;
// If I define variable_3 here!
$variable_3
// Would I be able to access it in function_B?
}
function_B(){
// Do something
$variable_4 = $variable_3
}
}
$myObj = new foo();
// Now what do I write in order to assign "variable_one" and "two" some value?
$myObj->$variable_one = 'some_value' ??
$myObj->$variable_two = 'some_value' ??
First, when you write simply $variable_one; inside A() it does not refer to the member variables of your class! That would be a completely different, newly created local variable called $variable_one bearing no relation to the class variable.
Instead, you want:
function A() {
$this->variable_one;
}
Second, your $variable_3 is also a local variable, and will not be accessible in any other function.
Third, your assignments at the bottom are correct in form, but not in syntax: there's an extra $ in there. You want:
$myObj->variable_one = 'some value';
No, $variable_3 was created (and will be destroyed) in the scope of function_A. This is due to function scope.
http://us3.php.net/manual/en/language.variables.scope.php
If you would like $variable_3 to be retained by your object once execution leaves function_A's scope, you need to assign it as a class property, similar to $variable_1 and $variable2.
class YourClass
{
public $variable_1;
public $variable_2;
public $variable_3;
function_A()
{
$this->variable_3 = "some value"; // assign to the object property
$variable_4 = "another value"; // will be local to this method only
}
function_B()
{
echo $this->variable_3; // Would output "some value"
echo $variable_4; // var does not exist within the scope of function_B
}
}
$myObj->variable_one = aValue;
$myObj->variable_two = anotherValue;
The correct code would be the following (see answer within comments)
class foo {
public $variable_one;
public $variable_two;
private $variable_three; // private because it is only used within the class
function _A(){
// using $this-> because you want to use the value you assigned at the
// bottom of the script. If you do not use $this-> in front of the variable,
// it will be a local variable, which means it will be only available inside
// the current function which in this case is _A
$this->variable_one;
$this->variable_two;
// You need to use $this-> here as well because the variable_3 is used in
// function _B
$this->variable_3;
}
function _B(){
// Do something
$variable_4 = $this->variable_3
}
}
$myObj = new foo();
$myObj->variable_one = 'some_value1'; // Notice no $ in front of the var name
$myObj->variable_two = 'some_value2'; // Notice no $ in front of the var name
Class variables (properties) must be accessed using the $this-> prefix, unless they are static (in your example they aren't). If you do not use the prefix $this-> they will be local variables within the function you define them.
I hope this helps!
If variable_one and variable_two are public, you can assign them as you specified (just remove the "$"...so $classObject->variable_one). Typically you want to encapsulate your variables by making them either protected or private:
class MyClass
{
protected $_variable_one;
public function getVariableOne()
{
return $this->_variable_one;
}
public function setVariableOne($value)
{
$this->_variable_one = $value;
}
}
$c = new MyClass();
$c->setVariableOne("hello!");
echo $c->getVariableOne(); // hello!

Categories