In following code after __toString() the php code is not working why ?
class Student{
private $name;
private $roll_no;
function __construct($name,$roll_no){
$this->name = $name;
$this->roll_no = $roll_no;
}
public function display(){
echo "Name :".$this->name;
echo "<br> Roll No :".$this->roll_no."<br><br>";
}
function __toString(){
$this->display();
}
}
$std1 = new Student("Bob" , 1);
echo $std1;
$std2 = new Student("John" , 2);
echo $std2;
$std3 = new Student("Tony" , 3);
echo $std3;
$std4 = new Student("Teena" , 4);
echo $std4;
The out put in browser is bellow : Name :Bob
Roll No :1 Rest of the lines are not working;
Try this
class Student{
private $name;
private $roll_no;
function __construct($name,$roll_no){
$this->name = $name;
$this->roll_no = $roll_no;
}
public function display(){
return "Name :".$this->name."<br> Roll No :".$this->roll_no."<br><br>";
}
function __toString(){
return $this->display();
}
}
$std1 = new Student("Bob" , 1);
echo $std1;
$std2 = new Student("John" , 2);
echo $std2;
$std3 = new Student("Tony" , 3);
echo $std3;
$std4 = new Student("Teena" , 4);
echo $std4;
Method __toString should return String not call output function. In Your code you done something like echo echo, because inside method display echo is called again. Change __toString to:
return $this->display();
and display method to:
return "Name :".$this->name."<br> Roll No :".$this->roll_no."<br><br>";
This solution fixes Your errors, but You should change display method name to something more matching its current behavior like getString().
Looking at naming conversion ( display method name ) most logical would be such approach:
class Student{
private $name;
private $roll_no;
function __construct($name,$roll_no){
$this->name = $name;
$this->roll_no = $roll_no;
}
public function display(){
echo $this; //conversion to string and echo
}
function __toString(){
return "Name :".$this->name."<br> Roll No :".$this->roll_no."<br><br>";
}
}
So I use inside display method conversion to String by __toString. Current usage would be:
$std1=new Student("Bob" , 1);
$std1.display();
//or the same:
echo $std1; //the same thing like $std1.display();
Related
I got some problem and I don't know how to fix it.
this is sample for the problem
class DancingClass {
private static $associate = [];
private static $first;
public static function first($param) {
self::$first = $param;
return new self;
}
public function second($param) {
self::$associate["second"] = $param;
return new self;
}
public function finish() {
var_dump(self::$associate["second"]);
$sec = self::$associate["second"] | "";
$all = self::$first . " ditemani oleh " . $sec;
return $all;
}
}
Then I call with chaining method
$callingClass = new DancingClass;
echo $callingClass::first("lucky")->second("adhitya")->finish(); // Return "lucky ditemani oleh adhitya"
echo "<br/>";
echo $callingClass::first("fatur")->finish(); // Return "fatur ditemani oleh"
but I got result like this
When you call second() method it sets variable on the same class instance that you call later.
Maybe you should try:
echo ((new DancingClass())->first(...)->second(...)->finish();
echo ((new DancingClass())->first(...)->finish()
I have a class called members, i have an example below. What i am asking is how do i set the values of title. So for example , i only allow Mr, Mrs, Miss and any other values will throw out an error stating Only Mr,Mrs,Miss is allowed , Firstname must be John..
class Member
{
private $title;
private $firstname;
public function __construct( $title )
{
$this->title = $title;
}
public function showProfile()
{
echo "<dl>";
echo "<dt>Title:</dt><dd>$this->title</dd>";
echo "</dl>";
}
}
$data = new Member( "Mrr" );
$data->showProfile();
You can try this , hope this will be helpful.
Try this code snippet here
<?php
ini_set("display_errors", 1);
class Member
{
private $title;
public function __construct($title)
{
if(!in_array($title, ["Mr","Mrs","Miss"]))
{
throw new Exception("Only Mr,Mrs,Miss are allowed!");
//or you can simple echo out your message instead of exception
}
$this->title = $title;
}
public function showProfile()
{
echo "<dl>";
echo "<dt>Title:</dt><dd>$this->title</dd>";
echo "</dl>";
}
}
$data = new Member("Mrr");
Optionally you can set a variable for this error with in the class, which prevent further execution of methods of class script. You can also do it like this
Solution 2:
Try this code snippet here
<?php
ini_set("display_errors", 1);
class Member
{
private $title;
private $error=false;
public function __construct($title)
{
if(!in_array($title, ["Mr","Mrs","Miss"]))
{
$this->error=true;
}
$this->title = $title;
}
public function showProfile()
{
if($this->error!==true)
{
echo "<dl>";
echo "<dt>Title:</dt><dd>$this->title</dd>";
echo "</dl>";
}
else
{
echo "Only Mr,Mrs,Miss is allowed!";
}
}
}
$data = new Member("Mrr");
$data->showProfile();
Make a setter
function setTitle($newTitle){
if(in_array($newTitle, array('Mr', 'Miss', 'Mrs' ))
$this->title=$newTitle;
else
echo 'ERROR';
}
And then call it from the constructor
I didnt like any of the answers.
Here's mine. I think you should use a mutator in your solution. The member class should be decoupled from the setter.
class Member
{
private $title;
public function setTitle($title)
{
$this->title = $title;
}
public function showProfile()
{
return sprintf("<dl><dt>Title</dt><dt><dd>%s</dd></dt></dl>" , $this->title );
}
}
class TitleProperty
{
protected $name = 'title';
protected $allowed_allowed = ['mr', 'mrs', 'miss'];
public $errors = [];
/**
*#param Member $member
*#param string $value
*/
public function __construct( Member $member, $value )
{
if(!in_array($value, $this->allowed_allowed )){
$this->errors[] = "Only Mr,Mrs,Miss is allowed";
}
else{
$member->setTitle( $value );
}
}
}
$member = new Member();
$property = new TitleProperty($member, 'hello');
if($property->errors){
print_r($property->errors);
}
else{
echo 'title set.';
}
There you go
How pass parameter to PHP class by class()::function()?
class greenHouse{
public function __construct(connection $con){
}
public function show(){
}
}
$nameclass = 'greenHouse';
$namefunction = 'show';
$nameclass::$namefunction();
works
$nameclass = 'greenHouse';
$namefunction = 'show';
$nameclass($con)::$namefunction();
doesn't work
I want to pass a parameter to the class with $nameclass($con)::$namefunction();. How do I do that in PHP?
You are trying to call a function statically with that notation...
$nameclass = 'greenHouse';
$namefunction = 'show';
$class = new $nameclass($con);
$class->$namefunction();
You can instantiate an object and immediately discard it by calling new within braces:
class Test
{
private $name;
function __construct($name)
{
$this->name = $name;
}
function speak()
{
echo $this->name;
}
function __destruct()
{
echo 'dead';
}
}
$class='Test';
$method='speak';
(new $class('David'))->$method();
echo ' is ';
$temp = new $class('John');
$temp->$method();
echo ' is ';
//Daviddead is John is dead
So in your case:
(new $nameclass($con))->$namefunction();
How do I initialize objects inside a function within a class? so I can call each object like page[0]->getTitle(); or page[1]->getDescription();
The error now says :
Fatal error: Using $this when not in object context in C:\xampp\htdocs\class.page.php on line 92
index.php
Page::createObjects();
and my page.class.php
private title;
private description;
private page;
public function __construct($title="", $description=""){
$this->title = $title;
$this->description = $description;
}
public static function createObjects(){
$database = new database();
$database->query('SELECT * FROM pages');
for($i=0;$i<$totalRows;$i++){
//line 92 here
$this->page[$i] = new self("Title", "Description");
}
}
You might consider having two different classes here, Page (page.class.php) and Pages (pages.class.php). Your Page class will represent an individual page record from your database, and your Pages class will contain methods that work on a set of records.
page.class.php
<?php
class Page
private title;
private description;
public function __construct($title="", $description=""){
$this->title = $title;
$this->description = $description;
}
public function getTitle()
{
return $this->title;
}
public function getDescription()
{
return $this->description();
}
}
?>
pages.class.php
<?php
class Pages
public static function createObjects(){
$pages = array();
$database = new database();
$database->query('SELECT * FROM pages');
for($i=0;$i<$totalRows;$i++){
//line 92 here
$pages[] = new Page("Title", "Description");
}
return $pages;
}
}
?>
Then in your index.php, you get your Page objects from Pages
index.php
<?php
$pages = Pages::createObjects();
// to get the title of the first object
echo $pages[0]->getTitle();
?>
Like others commented, you can't access $this from a static function
a static field/variable/property/method belong to the class, not to a specific instance
<?php
class VIP
{
private $name, $surname;
private static $vips = array();
function __construct($name, $surname){
$this->name = $name;
$this->surname = $surname;
self::$vips[] = $this;
}
function getCredentials(){
return $this->name . ", " . $this->surname;
}
static function getAll(){
return self::$vips;
}
}
$a = new VIP("George", "Clooney");
$b = new VIP("Scarlet", "Johansson");
$c = new VIP("Brad", "Pitt");
$d = new VIP("Emma", "Stone");
echo $a->getCredentials() . "\n";
foreach(VIP::getAll() as $vip)
echo $vip->getCredentials() . "\n";
?>
demo: https://eval.in/161874
however, this is more than likely bad code, since you are a beginner you should forget of static fields and methods and just use regular ones
better code:
<?php
class VIP
{
private $name, $surname;
function __construct($name, $surname){
$this->name = $name;
$this->surname = $surname;
}
function getCredentials(){
return $this->name . ", " . $this->surname;
}
}
class VIPsList
{
private $storage = [];
function add(VIP $vip){
$this->storage[] = $vip;
}
function getAll(){
return $this->storage;
}
}
$a = new VIP("George", "Clooney");
$b = new VIP("Scarlet", "Johansson");
$c = new VIP("Brad", "Pitt");
$d = new VIP("Emma", "Stone");
$collection = new VIPsList();
$collection->add($a);
$collection->add($b);
$collection->add($c);
$collection->add($d);
echo $a->getCredentials() . "\n";
foreach($collection->getAll() as $vip)
echo $vip->getCredentials() . "\n";
?>
https://eval.in/161898
I have a function w/in a function, and I need the inner function to make it's variables available in a scope of parent function, e.g.:
function sayMyName(){
getName(); // inner function generates $name value
echo $name; // use $name
}
sayMyName();
I could easily just globalize things w/in both functions... But my situation is far more complicated and handles more variables and globalizing each one is a bit tedious.
Thanks.
PS
i noticed a lot of "return" suggestions. sorry i wasnt clear , i need to return more variables.. not a simple return. thanks guys
You may use $_GLOBALS, but it`s a "bad practice". So,
1: Use return:
<?php
function getName(){
$name = 'Smith';
return $name;
}
function sayMyName(){
$name = getName();
echo $name;
}
sayMyName();
?>
Shows:
Smith
2: Use references:
<?php
function getName(&$name){
$name = 'Smith';
}
function sayMyName(){
getName($name);
echo $name;
}
sayMyName();
?>
Shows:
Smith
3: Return array for multiple variables:
<?php
function getName(){
$surname = 'Smith';
$name = 'John';
return array($surname, $name);
}
function sayMyName(){
list($surname, $name) = getName();
echo $name, ' ', $surname;
}
sayMyName();
?>
Shows:
John Smith
4. Return custom object for multiple variables:
<?php
function getName(){
$surname = 'Smith';
$name = 'John';
$buffer = new stdClass();
$buffer->name = $name;
$buffer->surname = $surname;
return $buffer;
}
function sayMyName(){
$obj = getName();
echo $obj->name, ' ', $obj->surname;
}
sayMyName();
?>
Shows:
John Smith
5. Use anonymous function with use statement and references:
<?php
function sayMyName(){
$surname = $name = 'Unknown';
$temp = function() use (&$name, &$surname){
$surname = 'Smith';
$name = 'John';
};
$temp();
echo $name, ' ', $surname;
}
sayMyName();
?>
Shows:
John Smith
do this
function sayMyName(){
$name = getName(); // inner function generates $name value
echo $name; // results will be returned
}
sayMyName();
I hope your inner function is returning name like this
function getName(){
return $name;
}
then it will work
This is what the object oriented programming was designed for. If many functions should share variables, it is probably best to encapsulate them to class like this:
class WhateverDescibestYourViewOfTheWorld {
protected $name;
function __construct( $name)
{
$this->name = $name;
}
function GetName() {
return $this->name;
}
function SayName()
{
echo $this->name;
}
}
// And use it:
$o = new WhateverDescibestYourViewOfTheWorld();
...
$o->SayName();
Or you can build class which will be just used as data container:
class DataContainer {
public $name;
public $address;
// ...
}
// By reference this will modify object previously created
function GetProperties( &$dataContainer) // Note that & isn't necessary since PHP5
{
$dataContainer->name = "...";
}
$c = new DataContainer();
GetProperties($c);
Or you can simplify this and use array:
function GetProperties( array &$dataContainer)
{
$dataContainer['name'] = '...';
}
$data = array();
GetProperties($data);
What about first assigning the return value of getName() to a variable?
$name = getName();
If you only need one variable you can do this
function getName(){
// Some code
return 'my name is XXX';
}
function sayMyName(){
$name = getName(); // inner function generates $name value
echo $name; // results to undefined
}
sayMyName();
Otherwise you may consider using a class : http://www.php.net/manual/en/language.oop5.php
You can use references
$param = "aaa";
function f(&$param)
{
//dostuff
inner($param);
echo $param;
}
function inner(&$inner) { //do other stuff }
or use return value
function f() { echo inner(); }
function inner($param) {return $param;}
if you work on references, both functions will work on same variable, not on a copy
http://php.net/manual/en/language.references.php
the best way would be with class
<?php
class Person
{
private $name;
public function setName($name){ $this->name = $name;}
public function sayName() {echo $this->name;}
}
$person = new Person();
$person->setName("Robert");
$person->sayName();
It's good way to make it in OOP.
That what you are thinking is wrong, however you can return an array of values. For ex:
function sayMyName()
{
$result = getName(); // inner function creates an array
echo $result['name'];
}
or better an object:
class Results
{
public $name;
}
function sayMyName()
{
$result = getName(); // inner function creating an object
echo $result->name;
}
You can also do it as below.
$name = "";
function sayMyName(){
getName(); // inner function generates $name value
//set $name variable inside getName() function.
echo $name; // results to undefined
}
sayMyName();
Please use bellow code ,it will solve your problem
global $var;
You can use it anywhere within your php span.