I have this code. And i need to print those strings. But i can't make changes outside the class. So i need to change inside class to work. The fields must remain private. Any ideas?
class STUDENT {
private $nume,$prenume;
# Constructor
public function __construct($nume , $prenume){
$this->nume=$nume;
$this->prenume=$prenume;
}
}
$student = new STUDENT("one","two");
echo "student: ". $student ."<hr/>";
You have to define __toString method. Then you can echo instance as string:
class STUDENT {
private $nume,$prenume;
public function __construct($nume , $prenume){
$this->nume=$nume;
$this->prenume=$prenume;
}
public function __toString()
{
return '{nume:'.$this->nume.','.prenume:'.$this->prenume.'}';
}
}
$student = new STUDENT("one","two");
echo "student: ". $student ."<hr/>";
You need to use getters and setters so the fields can be read and written. Here's a discussion on the subject: Getter and Setter?
Related
This is not a question about a particular problem, but rather a question asking for advice and / or assistance.
Im a 2nd year student, Im really struggling to get the hang of OOP programming, the fact that my textbook is not very clear, in its explanation is not helping either. I know there are 100's of examples on the web of this probably but I would like to focus specifically on the example used in my textbook.
The introduction to OOP in php starts with this:
EXAMPLE 1
class Person{
var $name;
function set_name($data){
$this->name=$data;
}
function get_name(){
return $this->name;
}
}
$ralph = new Person;
$ralph->set_name('Ralph');
echo 'friend name is '.$ralph->get_name();
Fine I get that no problem However it then goes on giving, what is in my view a very brief explanation on constructors, saying:
Wouldn't it be nice if you could both create and initialize an object at the same time, PHP allows you to do that with constructors.
And then proceeds to give the following example
EXAMPLE 2(UNCLEAR...?)
class Person{
var $name;
function __construct($data)
{
$this->name=$data
}
function set_name($data){
$this->name=$data;
}
function get_name(){
return $this->name;
}
}
$dan = new Person;
echo"Friend name is ", $dan->get_name(), ".";
My Question
I would really like to know what is the difference between the two examples above? Also if a beginner practical example could be included it will be enormously appreciated!
It's no wonder you are confused, that is a very bad example (looks like they forgot to include passing the name to the constructor)! There are also some outdated styles here as well, typically people do not use var anymore for property declarations but declare their scope (public, private, protected, etc.), also some syntax errors (missing semicolon), but that is for another day.
What would have made this a lot more clear is if they actually used the new power of the constructor, which for some reason, they did not. Here is an updated example where the constructor is actually being used:
class Person{
private $name;
function __construct($data)
{
$this->name=$data;
}
function set_name($data){
$this->name=$data;
}
function get_name(){
return $this->name;
}
}
// pass the name to the constructor and you can bypass the set_name call
$dan = new Person("Timothy");
echo "Friend name is ", $dan->get_name(), ".";
This definitely gets much more useful than passing scalars, but hopefully it illustrates what constructors can do a little bit better. Constructors are called automatically whenever you instantiate a new object from a class. Let me know if you have any questions.
The difference between two class is first one you can not initialize data at a time but in second class you can initialize data at a time.
In First Class
class Person{
private $name;
function set_name($data){
$this->name=$data;
}
function get_name(){
return $this->name;
}
}
$ralph = new Person; // you can not initialize value here
$ralph->set_name('Ralph');
echo 'friend name is '.$ralph->get_name(); //friend name is Ralph
In second Class
class Person{
private $name;
function __construct($data)
{
$this->name=$data
}
function set_name($data){
$this->name=$data;
}
function get_name(){
return $this->name;
}
}
$dan = new Person('Sahadat'); //you can initialize value here
echo"Friend name is ", $dan->get_name(), "."; //Friend name is Sahadat
$dan->set_name('John');
echo"Friend name is ", $dan->get_name(), "."; //Friend name is John
The second way is the best way.
Here is a simple answer. First you seem to use javascript var in the above code, so I omit this below. As you can see, the Person is the Object of concern. In the above example, the author is adding only a name to a Person object - but a person could have many other characteristics such as age, date of birth etc... So when a person object is initialized, the Person object will have a place to store its $name in memory. Since the the $name property is private, the above code uses setters and getters to set and get the $name property.
class Person{
private $name;
function setName($name){
$this->name = $name;
}
function getName(){
return $this->name;
}
function setName($name){
$this->name = $name;
}
}
$ralph = new Person;
$ralph->set_name('Ralph');
echo 'friend name is '.$ralph->get_name();
// Friend name is Ralph
The second example combines two steps ( btw you seem to have copied the wrong snippet ) the object will accept one parameter $data .
class Person{
private $name;
function __construct($data)
{
$this->name=$data
}
function setName($name){
$this->name=$name;
}
function getName(){
return $this->name;
}
}
$dan = new Person('Dan');
echo"Friend name is ", $dan->get_name(), ".";
//Friend name is Dan
A true object Oriented example should look like this:
class Person{
private $name;
function __construct($data)
{
$this->name=$data
}
function setName($name){
$this->name=$name;
return $this; // return $this to allow chaining of method calls
}
function getName(){
return $this->name;
}
}
Here is the extra, In real world applications, you find stuff like in this example
public function billTo(array $user){
// Create the Bill To info
$billto = new AnetAPI\CustomerAddressType();
$billto->setFirstName($user['firstname']);
$billto->setLastName($user['lastname']);
$billto->setCompany($user['company_name']);
$billto->setAddress($user['address']);
$billto->setCity($user['city']);
$billto->setState($user['state']);
$billto->setZip($user['zipcode']);
$billto->setCountry($user['country']);
$billto->setEmail($user['email']);
$billto->setPhoneNumber($user['phone']);
return $billto;
}
The above functions creates an instance of the class CustomerAddressType() and stores data from the User array ( passed as a parameter ) in that CustomerAddressType instance. Same as the first example given by the author.
I'm just experimenting with OOP programming I'm trying to create a form class. I'm unable to print the checkbox, how can I check where things are going wronge?
require_once('form.php');
$gender = new Checkbox('Please select your gender','gender',array('male','female'));
echo $gender->show_checkbox();
File with class:
class Inputfield{
public $id;
public $options_array;
public $question;
public $type;
function __construct($newquestion,$newid,$newoptions_array){
$this->question=$newquestion;
$this->id=$newid;
$this->type="txt";
$this->options_array=$newoptions_array;
}
public function show_options($options_arr,$type,$id,$classes){
$output="";
foreach($options_arr as $option){
$output.="<label for=\"".$option."\"></label><input name=\"".$option."\" type=\"".$type."\" id=\"".$id."\" class=\"".$classes."\">";
}
return $output;
}
public function show_question(){
$output="<h3 class='question'>".$this->vraag."</h3>";
return $output;
}
}
class Checkbox extends Inputfield{
function __construct($newquestion,$newid,$newoptions_array){
$this->question=$newquestion;
$this->id=$newid;
$this->type="checkbox";
$this->options_array=$newoptions_array;
}
public function show_checkbox(){
$output=show_question();
$output.=show_options($this->options_array,'checkbox',$this->id,'class');
return $output;
}
}
You call instance methods with $this: $this->show_options();
You don't need to copy-paste the whole constructor as soon as it's identical to the one in parent class
In case if it matches partially you can call it like parent::__construct(...) and then define a custom $this->type="checkbox";
You can not define it in runtime but specify it as a property default value.
You should use $this in an object context. Eg. in your show_checkbox method, write:
$output = $this->show_question();
$output .= $this->show_options(...);
I have a simple question regarding PHP Classes.
Multiple times I have seen other class-frameworks etc use method calls like.
$post->data->text();
I like this functionality, rather than just doing something like this.
$post->dataReturnAsText();
But i'm not quite sure how they created this functionality to have perhaps a 'sub-method'? Hope someone can point me in the right direction....
The example you provide has nothing special:
<?php
class Post{
public $data;
}
class Data{
public function text(){
}
}
$post = new Post;
$post->data = new Data;
$post->data->text();
However, you've probably found it in the context of method chaining (very popular in JavaScript libraries):
<?php
class Foo{
public function doThis(){
return $this;
}
public function doThat(){
return $this;
}
}
$foo = new Foo;
$foo->doThis()->doThat()->doThis();
In this case, data is simply a attribute of the class, and it contains another object:
class data
{
public function text()
{
}
}
class thing
{
public $data;
}
$thing = new thing();
$thing->data = new data();
$thing->data->text();
its probably a just that the "data" is a a public property of $post containing an object wth a text property for example :
class Textable {
public $text;
function __construct($intext) {
$this->text = $intext;
}
}
class Post {
public $data;
function __construct() {
$data = new Textable("jabberwocky");
}
}
this will allow you to do :
$post = new Post();
echo( $post->data->text ); // print out "jabberwocky"
of course the right OOP way is to make the property private and allow access useing a getter function but that besides the point...
I've recently started to work with OO PHP. As a training practice I'm trying to write some simple classes. I have trouble passing a variable from one to another class. Is it even possible?
class group
{
public $array = array();
public function person($name,$surname)
{
$this->person = new person($name,$surname);
}
public function __destruct()
{
print_r($this->array);
}
}
class person
{
public function __construct($name,$surname)
{
$this->name = $name;
$this->surname = $surname;
}
}
$A = new group();
$A->person("John","Doe");
What I want to archieve here is to pass person as another member of group (by simply putting it in group array) for further modifications and sorting. Been googling around but found nothing.
Please forgive me if it's a dumb one. ;)
I'm not sure I totally understand but I think you want:
Class group {
public $members=array();
public function person($name,$surname) {
$this->members[]=new person($name,$surname);
//Creates a new person object and adds it to the internal array.
}
/*...*/
}
A better alternative (seperation of intent) would be:
Class group {
public $members=array();
public function addPerson(person $p) {
$this->members[]=$p;
//Avoids this function need to know how to construct a person object
// which means you can change the constructor, or add other properties
// to the person object before passing it to this group.
}
/*...*/
}
The fix is changing
public function person($name,$surname)
{
$this->person = new person($name,$surname);
}
to
public function person($name,$surname)
{
$this->array[] = new person($name,$surname);
}
$this->person is not being stored in the array otherwise, and is overwritten with each call.
Your group class could improve it's OO by:
changing $array to be more descriptively named
changing the function name person to something more meaningful, like add_person
You should define your properties ('name', 'surname') and give them a suitability visibility
class group
{
public $array = array();
public name;
public surname;
...
Reference: http://php.net/manual/en/language.oop5.visibility.php
Say I have a simple class and I create it and call a function on it like this:
class tst
{
private $s = "";
public function __construct( $s )
{
$this->s = $s;
}
public function show()
{
return $this->s;
}
}
$t = new tst( "hello world" );
echo "showing " . $t->show() . "\n";
Is there any syntax or workaround that will allow me to instantiate an instance of tst and call the show() function without assigning the object to a variable? I want to do something like:
echo new tst( "again" )->show();
I don't want to declare my functions as static as I want to use them in both of the above examples.
You can't do what you want exactly, but there are workarounds without making things static.
You can make a function that returns the new object
function tst( $s ) {
return new tst( $s );
}
echo tst( "again" )->show();
To answer your question:
public static function create( $s )
{
return new tst($s);
}
public function show()
{
return $this->s;
}
The above will allow you to do tst::create("again")->show(). You can rename create as you like.
Agile Toolkit uses this approach everywhere. It uses add() method wrapper which is defined for global object ancestor. Here is some real-life code:
$page
->add('CRUD')
->setModel('User')
->setMasterField('admin',false);
This code creates 'CRUD' view, puts it on the page, creates and links with Model_User class instance which receives additional condition and default value for boolean 'admin' field.
It will display a CRUD control on the page with add/edit/delete allowing to edit all users except admins.
Here is code to describe concept:
class AbstractObject {
public $owner;
function add($class){
$c=new $class;
$c->owner=$this;
return $c;
}
}
class Form extends AbstractObject {
function dosomething(){
return $this;
}
}
class OtherForm extends Form {}
$object->add('Form')->dosomething()->owner
->add('OtherForm'); // etc
I think it's awesome and very practical approach.
p.s. I have to note new syntax for exceptions:
throw $this->exception('Something went bad');
using $this links exception to the object, which is at fault, which also can set default class for exception.