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();
Related
why can't i assign a function to a variable within a class: e.g
class call {
public $number = function() {
return 3 * 2;
}
}
$num = new call();
$num->number // expecting output 6
Is it possible to assign a method (function) to a property (variable) so that the method can be called outside the class just as a property. e.g
class call {
public $number = $this->value();
private function value() {
return 3 * 2;
}
}
$num = new call();
echo $num->$number // expecting output 6;
Use __get() magic method that called when you trying to get value of inaccessible properties
class call {
public function __get($name) {
if ($name == 'number')
return $this->value();
}
private function value() {
return 3 * 2;
}
}
$num = new call();
echo $num->number;
// 6
Consider the following case:
class Factory {
private $x = 1;
private $y = 2;
private $z = 3;
public function create(string $instance) {
return new $instance($this->x, $this->y, $this->z);
}
}
class A {
private $x;
public function __construct ($x) {
$this->x = $x;
}
public function display() {
echo "<pre>$this->x</pre>";
}
}
class B {
private $x;
private $y;
private $z;
public function __construct ($x, $y, $z) {
$this->x = $x;
$this->y = $y;
$this->z = $z;
}
public function display() {
echo "<pre>$this->x</pre>";
echo "<pre>$this->y</pre>";
echo "<pre>$this->z</pre>";
}
}
$factory = new Factory;
$a = $factory->create("A");
$a->display();
$b = $factory->create("B");
$b->display();
As you can see, the factory will always provide 3 arguments when it creates a new instance. But in the class A, only 1 argument is needed by the constructor. Since php does not have the usual method overloading, so this does not cause an issue. But just to be safe, should I add an argument list parameter to the contructor of class A something like :
public function __construct ($x, ... $ignore) { ... }
to catch those unnecessary arguments as I know it will get those additional arguments every time. Or is the existing code sufficient?
If you pass in more variables, than required in a functions definition, those extra variables will be ignored (sample: https://3v4l.org/fNfAQ).
But this might be an indication, that you are trying to do too much with this particular factory and you might have better results by using a DI container.
Or you might need to have separate factories, for creating instances with different dependencies, instead of making a singe "make everything" factory.
Instead of passing separate parameters, you could use an associative array for all the constructors.
class A {
private $x;
public function __construct ($params) {
$this->x = $params['x'];
}
public function display() {
echo "<pre>$this->x</pre>";
}
}
class B {
private $x;
private $y;
private $z;
public function __construct ($params) {
$this->x = $params['x'];
$this->y = $params['y'];
$this->z = $params['z'];
}
public function display() {
echo "<pre>$this->x</pre>";
echo "<pre>$this->y</pre>";
echo "<pre>$this->z</pre>";
}
}
Then the factory can do:
public function create($instance) {
return new $instance(array('x' => $this->x, 'y' => $this->y, 'z' => $this->z));
}
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();
I want to assign a value to a property of an object. I think it should be something like this:
$object->property = "value";
So, in my case I do:
$circle_obj->radius = 4;
So, I expected that property radius should be 4. Unfortunately, this is not the case in my situation. Can you understand why?
Below you can see my code.
<?php
class BaseClass{
public function calcSurface(){
//empty method
}
}
class Subclass_Circle extends BaseClass{
public $radius;
public function calcSurface(){
global $radius;
return M_PI * ($radius * $radius);
}
}
$circle_obj = new Subclass_Circle();
$circle_obj->radius = 4;
echo "Oppervlakte van circle is: " . $circle_obj->calcSurface(); //ouput: 0
echo "<br>";
class Subclass_Square extends BaseClass{
public $width;
public $height;
public function calcSurface(){
global $width;
global $height;
return $width * $height;
}
}
$square_obj = new Subclass_Square();
$square_obj->width = 4;
$square_obj->height = 4;
echo "Oppervlakte van vierkant is: " . $square_obj->calcSurface(); //output: 0
?>
You shouldn't be using global, but instead $this, like so:
public function calcSurface(){
return M_PI * ($this->radius * $this->radius);
}
Check out the PHP OOP tutorial for more information.
And look at the variable scope tutorial to better understand the global keyword.
when I run the below code I got error in line echo $attribute;
The error code: "Catchable fatal error: Object of class SomeShape could not be converted to string in ":
What wrong in this code?
Thanks.
<?php
class Shape
{
static public $width;
static public $height;
}
class SomeShape extends Shape
{
public function __construct()
{
$test=self::$width * self::$height;
echo $test;
return $test;
}
}
class SomeShape1 extends Shape
{
public function __construct()
{
return self::$height * self::$width * .5;
}
}
Shape::$width=60;
Shape::$height=5;
echo Shape::$height;
$attribute = new SomeShape;
echo $attribute;
$attribute1 = new SomeShape1;
echo $attribute1;
?>
What you are trying to do is echo an object, its like you are echoing an array(worst than echoing an array since echoing an object throuws error), while what you should be doing is accessing it's attribute or method etc. However if u wanna c what is in your object, you gotto use var_dump instead of echo .
In short, echo $attribute is wrong. Use var_dump($attribute)
Don't do a return in a constructor.
If you want to echo a value, trys to add a __toString() function (manual)
You cannot echo an object without implementing the __toString method.
Alternatively you could var_dump the object:
var_dump($attribute);
But what I think you are actually trying to do is more like this:
class Shape {
public $width;
public $height;
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
}
class SomeShape extends Shape {
public function getArea() {
return $this->width * $this->height;
}
}
class SomeShape1 extends Shape {
public function getHalfArea() {
return $this->width * $this->height * .5;
}
}
$shape = new SomeShape(10, 20);
echo $shape->getArea();
$shape = new SomeShape1(10, 20);
echo $shape->getHalfArea();
the solution that I found is:
I don't want to add more attribute to class shape but this solve my problem as I wish.may be there is more similar solution I will love to see. but this is my idea I define in class shape "public $attribute;" Inside the class SomeShape I wrote on "public function __construct()" "$this->attribute=self::$width * self::$height;" In the main scope I wrote "echo $object->attribute."";"
<?php
class Shape
{
static public $width;
static public $height;
public $attribute;
}
class SomeShape extends Shape
{
public function __construct()
{
$this->attribute=self::$width * self::$height;
}
}
class SomeShape1 extends Shape
{
public function __construct()
{
$this->attribute=self::$width * self::$height * .5;
}
}
Shape::$width=60;
Shape::$height=5;
$object = new SomeShape;
echo $object->attribute."<br />";
$object1 = new SomeShape1;
echo $object1->attribute;
?>