Initialize a class property - php

Is there a way to initialize a PHP class property from another class property? I have a series of properties I'd like to depend upon each other for easy modification of the root value:
class Anon {
private static $a = 5;
private static $b = '+' . (2 * self::$a);
}
However, this causes a syntax error. I've had trouble searching for this, but I haven't seen anybody trying to do this!

You can initialise the static variable by using an Init method
<?php
class Anon {
private static $a = 5;
private static $b ;
public static function Init(){
self::$b = '+' . (2 * self::$a);
}
public static function getB(){
return self::$b;
}
}
Anon::Init();
echo Anon::getB();
?>

Depends on how you're using the class, but maybe this will help:
class Anon {
private static $a = 5;
private static $b;
function __construct() {
self::$b = '+' . (2 * self::$a);
}
public function getB() {
return self::$b;
}
}
$anon = new Anon;
echo $anon->getB();

Unfortunately PHP can not parse non-trivial expression while class is being loaded
Here is a solution to initialize your static members
class Anon {
private static $a;
private static $b;
public static function init () {
self::$a = 5;
self::$b = '+' . (2 * self::$a);
}
}
Anon::init();

You can't access private class properties directly. You can with public though.
class Anon {
public static $a = 5;
}
print Anon::$a;
or use a public function like the other examples to access $b;
class Anon {
private static $a = 5;
private static $b;
public static function init() {
return self::$b = '+' . (2 * self::$a);
}
}
echo Anon::init();

Related

Extended classes and undefined Variables - PHP [duplicate]

This question already has answers here:
PHP - Private class variables giving error: undefined variable
(4 answers)
Closed 4 years ago.
Square and Rectangle are classes that extends abstract class ShapesClass, defining their own Area methods.
abstract class ShapesClass
{
// Force Extending class to define this method
abstract public function Area();
}
class Square extends ShapesClass
{
private $side = 0;
function __construct($n)
{
$side = $n;
}
function Area()
{
echo $side * $side;
}
}
class Rectangle extends ShapesClass
{
var $length = 0;
var $width = 0;
function __construct($a,$b)
{
$length = $a;
$width = $b;
}
function Area()
{
echo $length * $width;
}
}
$listShapes = array();
$listShapes[0] = new Square(3);
$listShapes[1] = new Rectangle(3,4);
$listShapes[0]->Area();
$listShapes[1]->Area();
I get undefined variable errors on side, length and width.
Doesn't these three variables have default values and are also set by the constructor.
You actually want to refer to them as $this->foo
function __construct($a,$b)
{
$this->length = $a;
$this->width = $b;
}
Basically $foo acts like a local, variable, scoped to current method. $this->foo acts like a instance variable, which is available anywhere in the class.
In your code whenever we create variables for any class we can call them inside methods with the class reference only i.e. $this
Also, in php we can define the variables with var there are public, protected and private keywords to define any variable.
So, you can update your code with the below code
abstract class ShapesClass
{
// Force Extending class to define this method
abstract public function Area();
}
class Square extends ShapesClass
{
private $side = 0;
function __construct($n)
{
$this->side = $n;
}
function Area()
{
echo $this->side * $this->side;
}
}
class Rectangle extends ShapesClass {
private $length = 0;
private $width = 0;
function __construct($a,$b)
{
$this->length = $a;
$this->width = $b;
}
function Area()
{
echo $this->length * $this->width;
}
}
$listShapes = array();
$listShapes[0] = new Square(3);
$listShapes[1] = new Rectangle(3,4);
$listShapes[0]->Area();
$listShapes[1]->Area();

Cannot re-assign $this: Use reference of an existing object A into another object B which class extends the one of object A

In PHP (Symfony 3);
I want to reference an existing object A in another object B which class extends the one of object A, like this:
class A {
private $property1;
private $property2;
public function __construct($p1,$p2){
$this->property1 = $p1;
$this->property2 = $p2;
}
}
class B extends A {
private $property3;
public function __construct($objectA,$p3){
$this = $objectA;
$this->property3 = $p3;
}
}
$a = new A('p1','p2');
$b = new B($a,'p3');
This does not work and throw the following error at the statement $this = $objectA:
Compile Error: Cannot re-assign $this
Which are documented and explain there and there. I am looking for a workaround.
You must call parent constructor and also make property1 and property2 visible in class B
<?php
class A {
private $property1;
private $property2;
public function __construct($p1,$p2){
$this->property1 = $p1;
$this->property2 = $p2;
}
public function getProperty1()
{
return $this->property1;
}
public function getProperty2()
{
return $this->property2;
}
}
class B extends A {
private $property3;
public function __construct($objectA,$p3){
parent::__construct($objectA->getProperty1(), $objectA->getProperty2());
$this->property3 = $p3;
}
}
$a = new A('p1','p2');
$b = new B($a,'p3');
See it live here: http://sandbox.onlinephpfunctions.com/code/705bf1827da2bdf10f8d961ee1cb6fbdd88bc663
As an alternative, you could use __call magic method to forward all cals to class A:
<?php
class A {
private $property1;
private $property2;
public function __construct($p1,$p2){
$this->property1 = $p1;
$this->property2 = $p2;
}
}
class B extends A {
private $property3;
private $a;
public function __construct($objectA,$p3){
$this->a = $objectA;
$this->property3 = $p3;
}
public function __call($name, $arguments)
{
return call_user_func_array(array($this->a, $name), $arguments);
}
}
$a = new A('p1','p2');
$b = new B($a,'p3');
Based on how to clone object to child class in php
Using get_object_vars on the parent object, you can get an array of properties keys and values. You can then loop through them and assign them to the child object:
<?php
class A {
protected $property1;
protected $property2;
public function __construct($p1,$p2){
$this->property1 = $p1;
$this->property2 = $p2;
}
}
class B extends A {
private $property3;
public function __construct($objectA,$p3){
//$this = $objectA;
$objValues = get_object_vars($objectA); // return array of object values
foreach($objValues AS $key=>$value)
{
$this->$key = $value;
}
$this->property3 = $p3;
echo $this->property1;
}
}
$a = new A('p1','p2');
$b = new B($a,'p3');
This does not work with private properties, they need to be at least of protected level.
I ended up managing it like that:
class B extends A{
public function __construct($objectA){
foreach($this as $k => $v){
if(isset($objectA->{$k})){
$this->{$k} = &$objectA->{$k};
}
}
}
}
Compare to #Antony answer, notice it has & in front of $objectA->{$k}: $this->{$k} = &$objectA->{$k};. As I understood it, with &, any change on $objectB of properties belonging to the extended class A applies to $objectA.
I am aware it is not perfect and quite hacky but it does the job I need. Thanks for the input given by everybody.

PHP : Can I affect a type when declaration of variable in class?

I would declare a private var in my class with a specific type like this :
class MyClass
{
private (int) $myvar;
private (MyObject) $instance;
function __construct()
{
$this->myvar = 2;
$this->instance = new MyObject;
}
}
But it doesn't work and it seems there is no way to do what I want.
No need of type Casting. do like this
class MyClass
{
private $myvar;
private $instance;
function __construct()
{
$this->myvar = 2;
$this->instance = new MyObject;
}
}

PHP Fatal error: Using $this when not in object context in C:/xampp/htdocs/oops/1.php on line 9?

I need to assign b value in a inside the method onec, but its failing. Please let me know what I am doing wrong here:
<?php
class One {
public $a = 10;
public $b = 20;
public static function onec() {
$this->a = $this->b;
return $this->a;
}
}
echo One::onec();
?>
Use the self keyword. The $this keyword is not accessible under static context. Also, you should make your variables static
Like this..
<?php
class One {
public static $a = 10;
public static $b = 20;
public static function onec() {
self::$a = self::$b;
return self::$a;
}
}
echo One::onec();
You use $this in static function.
http://www.php.net/manual/en/language.oop5.static.php
<?php
class One {
public $a = 10;
public $b = 20;
public static function onec() {
$obj = new One();
$obj->a = $obj->b;
return $obj->a;
}
}
echo One::onec();
Use this code
class One {
public $a = 10;
public $b = 20;
public function onec() {
$this->a = $this->b;
return $this->a;
}
}
$obj = new One();
echo $obj->onec();

Calling method on all instances of class

I am looking for a way to call a function on all instances of a class preferably via a static method call.
Example:
class number{
private $number;
static function addAll(){
//add all of the values from each instance together
}
function __construct($number){
$this->number = $number;
}
}
$one = new number(1);
$five = new number(5);
//Expecting $sum to be 6
$sum = number::addAll();
Any help on this would be greatly appreciated. Thanks!
It can be done like this:
class MyClass {
protected $number;
protected static $instances = array();
public function __construct($number) {
// store a reference of every created object
static::$instances [spl_object_hash($this)]= $this;
$this->number = $number;
}
public function __destruct() {
// don't forget to remove objects if they are destructed
unset(static::$instances [spl_object_hash($this)]);
}
/**
* Returns the number. Not necessary here, just because
* you asked for an object method call in the headline
* question.
*/
public function number() {
return $this->number;
}
/**
* Get's the sum from all instances
*/
public static function sumAll() {
$sum = 0;
// call function for each instance
foreach(static::$instances as $hash => $i) {
$sum += $i->number();
}
return $sum;
}
}

Categories