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

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;

Related

Echo variable which has been set in another classes function

I am trying to access the contents of a variable from another class. I have the code below, I am expecting to get 'test' returned, I get nothing.
I assume this is because it is getting $abc_rank as empty. It is required that the variable is populated in the function itself.
Therefore how can I get $abc_rank to hold that echo and output via the other class?
<?php
class class1 {
public static $abc_rank;
public function __construct() {
$this->add_text();
}
public function add_text() {
$this->abc_rank = 'test';
}
}
class class2 {
public function __construct() {
$this->display();
}
public function display() {
$test = class1::$abc_rank;
echo $test;
}
}
$go = new class2();
?>
I know I can do:
public static $abc_rank = 'test';
But the population of the variable must be in a function.
I have read some of the other related answers and can't seem to get this to work.
In class1 :
Replace $this->abc_rank = 'test'; with $this::$abc_rank='test';
($abc_rank is a static property)
In class2 :
In your display function : replace
$test = class1::$abc_rank;
echo $test;
with
$test = new class1();
echo $test::$abc_rank;
(class1 isn't static)
Full code here :
class class1 {
public static $abc_rank;
public function __construct() {
$this->add_text();
}
public function add_text() {
//$this->abc_rank = 'test';
$this::$abc_rank='test';
}
}
class class2 {
public function __construct() {
$this->display();
}
public function display() {
//$test = class1::$abc_rank;
//echo $test;
$test = new class1();
echo $test::$abc_rank;
}
}
$go = new class2();
you have to create the class1 to run the constructor of this class.
class class1 {
public static $abc_rank;
public function __construct() {
$this->add_text();
}
public function add_text() {
self::$abc_rank = 'test';
}
}
class class2 {
public function __construct() {
$this->display();
}
public function display() {
$test = class1::$abc_rank;
echo $test;
}
}
new class1();
$go = new class2();

Switch visibility in php if parameter

I'm wondering if its possible to switch the visibility in PHP. Let me demonstrate:
class One {
function __construct($id){
if(is_numeric($id)){
//Test function becomes public instead of private.
}
}
private function test(){
//This is a private function but if $id is numeric this is a public function
}
}
Is such thing even possible?
I would use an abstract class with two implementing classes: One for numeric and one for non-numeric:
abstract class One {
static function generate($id) {
return is_numeric($id) ? new OneNumeric($id) : new OneNonNumeric($id);
}
private function __construct($id) {
$this->id = $id;
}
}
class OneNumeric extends One {
private function test() {
}
}
class OneNonNumeric extends One {
public function test() {
}
}
$numeric = One::generate(5);
$non_numeric = One::generate('not a number');
$non_numeric->test(); //works
$numeric->test(); //fatal error
It can be faked up to a point with magic methods:
<?php
class One {
private $test_is_public = false;
function __construct($id){
if(is_numeric($id)){
$this->test_is_public = true;
}
}
private function test(){
echo "test() was called\n";
}
public function __call($name, $arguments){
if( $name=='test' && $this->test_is_public ){
return $this->test();
}else{
throw new LogicException("Method $name() does not exist or is not public\n");
}
}
}
echo "Test should be public:\n";
$numeric = new One('123e20');
$numeric->test();
echo "Test should be private:\n";
$non_numeric = new One('foo');
$non_numeric->test();
I haven't thought about the side effects. Probably, it's only useful as mere proof of concept.

passing variables from a protected function to a public function inside the same class in php

I have a class and two functions inside it as follows:
class MyClassName
{
protected function myFunction1()
{
// some code here
return $something;
}
public function myFunction2()
{
// some code here
return $somethingElse;
}
}
What I need to do is define a variable in myFunction1() and then use it in myFunction2(). What is the best practice to do that?
class MyClassName
{
public $var = 0;
protected function myFunction1()
{
// some code here
$this->var = ...;
return $something;
}
public function myFunction2()
{
// some code here
echo $this->var;
return $somethingElse;
}
}
Actually vars should be defined out of the function and then set a value. Then can be modified over all the script, by doing this->var
Make it a class property
class MyClassName
{
private $property;
public function __construct() {
$this->myFunction1();
}
protected function myFunction1()
{
// some code here
$this->property = 'an apple';
}
public function myFunction2()
{
// some code here
return $this->property;
}
}
Now test it:
$my_class = new MyClassName();
$something = $my_class->myFunction2();
echo $something;

PHP: How do I access a local varibale of a function in class from another function

So i have a php class and i'm having a small snarl up. imagine a class as one shown below
<?php
class Foo
{
public function __construct()
{
$this->bar1();
}
public function bar1()
{
$myvar = 'Booya!';
return 'Something different';
}
public function bar2()
{
//get value of $myvar from bar1()
}
}
$new_foo = new Foo();
$new_foo->bar2();
?>
Question is,
how do I access the variable $myvar from bar1() keeping in mind that bar1() returns something different.
You would do something like this... Everything has been explained through comments next to the code.
<?php
class Foo
{
private $myvar; //<---- Declare the variable !
public function __construct()
{
$this->bar1();
}
public function bar1()
{
$this->myvar = 'Booya!'; //<---- Use this $this keyword
//return 'Something different';//<--- Comment it.. Its not required !
}
public function bar2()
{
return $this->myvar; //<----- You need to add the return keyword
}
}
$new_foo = new Foo();
echo $new_foo->bar2(); //"prints" Booya!
<?php
class Foo
{
var $myvar;
public function __construct()
{
$this->bar1();
}
public function bar1()
{
$this->myvar = 'Booya!';
return 'Something different';
}
public function bar2()
{
//get value of $myvar from bar1()
echo $this->myvar;
}
}
$new_foo = new Foo();
$new_foo->bar2();
?>
You should set it as a class variable first, then access it using $this
You cannot do that directly, only you can do without altering bar1() return value is create a
class variable for saving the value of this data
In class definition add
private $saved_data;
In bar1():
$myvar = 'Booya!';
$this->saved_data = $myvar;
And in bar2()
$myvar_from_bar1 = $this->saved_data
Use class variables like:
$this->myvar = 'Booya!';
Now the variable myvar will be store in the class and can be requested or altered in other methods.

PHP Object Oriented Issue On My Code

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().

Categories