PHP Object Oriented Issue On My Code - php

Hi please have a look on bellow code.
<?php
class A
{
public $name;
public function getName()
{
return $this->name;
}
}
class B extends A
{
public function setName()
{
$this->name = 'Prasad';
}
}
$obj = new B();
echo $obj->getName();
?>
Here It's display nothing when I echo the name. Related to the $name in class A. Is this issue is with getName or setName? How can I set the $name variable in class A from extended class B. And how can I get that from a class B object. Appreciate any hint or explanation on what I have missed.

You didn't set the name (using $obj->setName()) before.

Technically, it's echoing the $name variable (which is undefined at that point). Unfortunately, it hasn't been set yet. Try using $obj->setName() to set the name.

You are most of the way there with your code, in fact you would have a working example if you added a line telling the code to call the setName() function:
$obj = new B();
$obj->setName();
echo $obj->getName();
More typically you would use a set function with a parameter, then pass the value you want to set. You would also set the $name property to protected, which means the value must be accessed via the set & get methods (more on visibility in the manual):
<?php
class A
{
protected $name;
public function getName()
{
return $this->name;
}
}
class B extends A
{
public function setName($name)
{
$this->name = $name;
}
}
$obj = new B();
$obj->setName('Prasad');
echo $obj->getName();
?>

Yes, as SomeKittens suggested you need to call setName() first.
class A
{
public $name;
public function getName()
{
return $this->name;
}
}
class B extends A
{
public function setName()
{
$this->name = 'Prasad';
}
}
$obj = new B();
$obj->setName();
echo $obj->getName();
However, it might be better to perform the setting of the name in the constructor of B, as:
class A
{
public $name;
public function getName()
{
return $this->name;
}
}
class B extends A
{
public function B()
{
$this->name = 'Prasad';
}
}
$obj = new B();
echo $obj->getName();
This printed Prasad for me using http://writecodeonline.com/php/ to test the code.
Even better, pass the name 'Prasad' when creating the new B object, as:
class A
{
public $name;
public function getName()
{
return $this->name;
}
}
class B extends A
{
public function B( $value = 'Prasad' )
{
$this->name = $value;
}
}
$obj = new B();
echo $obj->getName(), "<br>";
$obj = new B( 'John' );
echo $obj->getName();

It's because you aren't setting the name attribute first. Call B->setName() and then you can get the name by calling B->getName().

Related

PHP how set default value to a variable in the class?

class A{
public $name;
public function __construct() {
$this->name = 'first';
}
public function test1(){
if(!empty($_POST["name"]))
{
$name = 'second';
}
echo $name;
}
$f = new A;
$f->test1();
Why don't we get first and how set right default value variable $name only for class A?
I would be grateful for any help.
You can use a constructor to set the initial values (or pretty much do anything for that matter) as you need to like this:
class example
{
public $name;
public function __construct()
{
$this->name="first";
}
}
Then you can use these default values in your other functions.
class example
{
public $name;
public function __construct()
{
$this->name="first";
}
public function test1($inputName)
{
if(!empty($inputName))
{
$this->name=$inputName;
}
echo "The name is ".$this->name."\r\n";
}
}
$ex=new example();
$ex->test1(" "); // prints first.
$ex->test1("Bobby"); // prints Bobby
$ex->test1($_POST["name"]); // works as you expected it to.
you have two options to set the default values for the class attributes:
Option 1: set at the parameter level.
class A
{
public $name = "first";
public function test1()
{
echo $this->name;
}
}
$f = new A();
$f->test1();
Option 2: the magic method __construct() always being executed each time that you create a new instance.
class A
{
public $name;
public function __construct()
{
$this->name = 'first';
}
public function test1()
{
echo $this->name;
}
}
$f = new A();
$f->test1();
Use isset() to assign a default to a variable that may already have a value:
if (! isset($cars)) {
$cars = $default_cars;
}
Use the ternary (a ? b : c) operator to give a new variable a (possibly default) value:
$cars = isset($_GET['cars']) ? $_GET['cars'] : $default_cars;

How to display a class from another class in PHP

How to display a class from another class in PHP ?
class Layout {
public $var;
public function __construct() {
$this->var = 'test';
}
public function __toString() {
return $this->var;
}
}
class Template {
private $var_layout;
public function __construct() {
$obj = new Layout;
$this->var_layout = $obj;
}
public function __toString() {
return $this->var_layout;
}
}
$template = new Template();
echo($template);
Error message: Method Template::__toString() must return a string value
Please help, thank you very much..
return $this->var_layout; in the Template class does not return a string, it returns an object. Make it return a string by calling the __toString() method of that object explicitly.

Getting class of variable

How can I figure out in what class a reference to a variable was initiated (and currently exists)?
Example:
<?php
class MyClass {
public $array = array(
"this",
"is",
"an",
"array"
);
}
$class = new MyClass();
$arrayReference = &$class->array;
GetClassForVariable($arrayReference); //Should return "MyClass"
?>
My best bet is some kind of Reflection, but I haven't found any functions that seem suitable for this.
Edit:
A better suited example for what I want is the following:
<?php
class API_Module {
public $module;
public $name;
private $methods = array();
public function __construct($module, $name) {
$this->module = $module;
$this->name = $name;
$this->methods["login"] = new API_Method($this, "login", "Login");
}
public function GetMethod($method) {
return $this->methods[$method];
}
public function GetURL() {
return $this->module; //Should return "session"
}
}
class API_Method {
public $method;
public $name;
private $parentReference;
private $variables = array();
public function __construct(&$parentReference, $method, $name) {
$this->parentReference = $parentReference;
$this->method = $method;
$this->name = $name;
$this->variables["myvar"] = new API_Variable($this, "myvar");
}
public function GetURL() {
return $this->GetParentURL() . "/" . $this->method; //Should return "session/login"
}
public function GetVariable($variableName) {
return $this->variables[$variableName];
}
private function GetParentURL() {
// Need to reference the class parent here
return $this->parentReference->GetURL();
}
}
class API_Variable {
public $name;
private $parentReference;
public function __construct(&$parentReference, $name) {
$this->parentReference = $parentReference;
$this->name = $name;
}
public function GetURL() {
return $this->GetParentURL() . "/" . $this->name; //Should return "session/login/myvar"
}
private function GetParentURL() {
// Need to reference the class parent here
return $this->parentReference->GetURL();
}
}
$sessionModule = new API_Module("session", "Session");
var_dump($sessionModule->GetMethod("login")->GetVariable("myvar")->GetURL()); //Should return "session/login/myvar"
?>
Now, this works fine, but I'd love to be able to do this without using $parentReference in every single subvariable. It might not be possible, but I'd love to know whether it is or not.
For your example:
$class = new MyClass();
$arrayReference = &$class->array;
GetClassForVariable($arrayReference); //Should return "MyClass"
to find out to which variable originally the alias $arrayReference refers to is not possible in PHP. There is no function available resolving the aliases.
Additionally $class->array is just a variable on it's own. So you would also need to find out based on a value in which class it was defined. That is not possible as well, similar to that PHP does not offer anything to resolve a variable alias, it also does not offer anything to learn about the definition of a variable.
So in short PHP does not have a ReflectionVariable class available ;) I wonder if it is even possible.
The get_class() function should work:
http://php.net/manual/en/function.get-class.php
I agree with GRoNGoR that you shouldn't need to get the parent class of a property of an instantiated object. You could instead just get the name of the class before accessing the property. For example:
$class = new MyClass();
$parent_class = get_class($class); // returns "MyClass"
$arrayReference = &$class->array;
Not sure why you'd need the parent class of the property when you have the object instance and can easily get the parent class from there.

Use method of parent class when extending

Probably a silly question.. but how do I correctly use the methods of class Test in class Testb without overriding them?
<?php
class Test {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
<?php
class Testb extends Test {
public function __construct() {
parent::__construct($name);
}
}
<?php
include('test.php');
include('testb.php');
$a = new Test('John');
$b = new Testb('Batman');
echo $b->getName();
You need to give the Testb constructor a $name parameter too if you want to be able to initialize it with that argument. I modified your Testb class so that its constructor actually takes an argument. The way you currently have it, you should not be able to initialize your Testb class. I use the code as follows:
<?php
class Test {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class Testb extends Test {
// I added the $name parameter to this constructor as well
// before it was blank.
public function __construct($name) {
parent::__construct($name);
}
}
$a = new Test('John');
$b = new Testb('Batman');
echo $a->getName();
echo $b->getName();
?>
Perhaps you do not have error reporting enabled? In any event, you can verify my results here: http://ideone.com/MHP2oX

transfer variables between class A and B

How i can run method $this->ob->getVar() inside class B function C here ? I get no. Did i must transfer string to constructor ?
<?php
class A{
public $tabb = array('1'=>'one', '2'=>'two');
public $index;
public function setVar($v){
$this->index = $v;
}
public function getVar(){
return $this->index;
}
public function arr(){
return $this->tabb;
}
}
class B{
public $tab;
public function __construct($var){
$this->ob=new A;
$this->tab = $var;
}
public function C(){
return $this->D($this->tab, $this->ob->getVar());
}
public function D($l, $j){
if(is_array($l) && isset($j)){
print 'yes';
} else {
print 'no';
}
}
}
$obb = new A;
$obb->setVar('onetwo');
$k = $obb->arr();
$obbb = new B($k);
$obbb->C();
?>
First, for the sake of convention your B class should declare a private variable of $obj, but that is not necessary in PHP.
Second, your B class is just creating a new instance of A in its constructor. So you have two different A classes. The once inside B never has its index property populated.
If you wanted to have the A object created outside the B object you'll have to pass it in like this:
$obbb = new B($k, $obb);
So now your new B constructor is something like this:
public function __construct($var, $someObject){
if (!empty($someObject)) {
$this->ob = $someObject;
}
else {
$this->ob=new A;
}
$this->tab = $var;
}

Categories