Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
It's been a while since I last work with object. I can't figure out what I did wrong. I have a class that contain another class as a property. After instantiating ItemDetail() inside Item(), I can't get the value of description. var_dump($item) give me NULL for the value of $detail. Please help. Thank you.
<?php
class Item
{
private $name;
private $detail;
function __construct() {
$this->name = 'some name';
$this->detail = new ItemDetail();
}
function getDetail() {
return $this->detail;
}
}
class ItemDetail
{
private $description;
function __construct() {
$this->description = 'some description';
}
function getDescription {
return $this->description;
}
}
$item = new Item();
echo $item->getDetail()->getDescription();
//var_dump($item);
?>
You need to change the scope of your class properties, or define a method that returns the values. Example:
class Item
{
private $name;
private $detail;
function __construct() {
$this->name = 'some name';
$this->detail = new ItemDetail();
}
public function getDescription() {
return $this->detail->getDescription();
}
}
class ItemDetail
{
private $description;
function __construct() {
$this->description = 'some description';
}
public function getDescription() {
return $this->description;
}
}
$item = new Item();
echo $item->getDescription();
If you make your properties public, you can get them like this as well:
class Item
{
public $name;
public $detail;
public function __construct() {
$this->name = 'some name';
$this->detail = new ItemDetail();
}
}
class ItemDetail
{
public $description;
public function __construct() {
$this->description = 'some description';
}
}
$item = new Item();
echo $item->detail->description;
It's all about visibility
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
I am trying to convert a simple class object to json as string.
It does not work!. could you help me please.
here are my files:
Peson.php
<?php
class Person
{
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function toJson()
{
return json_encode($this);
}
}
?>
index.php
include 'Person.php';
$person = new Person();
$person->setName("John");
echo $person->toJson();
Result :
You're getting an empty object because your class doesn't have any public properties to encode. Change name from private to public and you'll get output like this: {"name":"John"}
You can use get_object_vars for this.
public function toJson()
{
return json_encode(get_object_vars($this)); //returns {"name":"stringNameHere"}
}
More info about get_object_vars here.
This is how your code would look:
class Person
{
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function toJson()
{
return json_encode(get_object_vars($this));
}
}
$person = new Person();
$person->setName('testName');
echo $person->toJson(); //Print {"name":"testName"}
Here you have a live code example
In this case you get an empty object because the properties are private. A way to keep your properties private and still geting their values in a JSON is using the JsonSerializable Interface. Then implementing its method jsonSerialize().
class Person implements JsonSerializable
{
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function jsonSerialize()
{
$vars = get_object_vars($this);
return $vars;
}
}
<?php
class Person implements \JsonSerializable
{
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function jsonSerialize()
{
return get_object_vars($this);
}
}
?>
then, you can convert your person object to JSON with json_encode
$person = new Person();
$person->setName("John");
echo json_encode($person);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I had one lesson in OOP which included messaging between classes. On the tutorial, the guy just showed var_dump output version of that. I wanted to play with the code and change from var_dump to echo output, because it would me more useful in future. I just couldn't find any solution so you guys are my only option. Here's the code.
<?php
class Person {
protected $name;
public function __construct($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
class Business {
// adding Staff class to Business
public function __construct(Staff $staff)
{
$this->staff = $staff;
}
// manual hire(adding Person to Staff)
public function hire(Person $person)
{
// add to staff
$this->staff->add($person);
}
// fetch members
public function getStaffMembers()
{
return $this->staff->members();
}
}
class Staff {
// adding people from Person class to "member" variable
protected $members = [];
public function __construct($members = [])
{
$this->members = $members;
}
// adding person to members
public function add(Person $person)
{
$this->members[] = $person;
}
public function members()
{
return $this->members;
}
}
// you can also create an array with this method
$bros = [
'Bro',
'Zdenko',
'Miljan',
'Kesten'
];
// pretty simple to understand this part
$employees = new Person([$bros]);
$staff = new Staff([$employees]);
$business = new Business($staff);
var_dump($business->getStaffMembers());
// or the print_r, it doesn't matter
print_r($business->getStaffMembers());
?>
Try to loop through the array and echo out every single value.
$array = $something //your assignment here
foreach($array as $key => $value ){
echo "$key => $value\n";
}
I am trying to pass a class as a parameter but I do not know if it is possible.
class User {
var $name;
}
class UserRepository {
private $type;
public function __construct(Class) {
$this->type = Class;
}
public function getInstance() {
return new $this->type;
}
}
$obj = new UserRepository(User);
I am accepting suggestions on other ways to do it as well.
Just instantiate the class and call that
$user = new User();
$obj = new UserRepository($user);
Another option (since User contains only variables) is to make the variable static and use that
class User {
public static $name;
}
$obj = new UserRepository(User::$name);
I think you are just looking for a string:
class User {
var $name;
}
class UserRepository {
private $type;
public function __construct($Class) {
^^^^^^ this will be a string
$this->type = $Class;
}
public function getInstance() {
return new $this->type;
}
}
$obj = new UserRepository('User');
^^^^^^ send a string here
var_dump($obj->getInstance());
output:
object(User)#2 (1) { ["name"]=> NULL }
An example.
class Author {
private $firstName;
private $lastName;
public function __construct($firstName, $lastName) {
$this->firstName = $firstName;
$this->lastName = $lastName;
}
public function getFirstName() {
return $this->firstName;
}
public function getLastName() {
return $this->lastName;
}
}
class Question {
private $author;
private $question;
public function __construct($question, Author $author) {
$this->author = $author;
$this->question = $question;
}
public function getAuthor() {
return $this->author;
}
public function getQuestion() {
return $this->question;
}
}
Class author is injected into the constructor of Question class am I correct? but how to call the Question class to get the author's name?
$question = new Question('What is PHP', 'Adam');
$question->getFirstname;
like this? I assume Question class inherited Author class so Question's instance can use the function of Author Class?
Simple
echo $question->getAuthor()->getFirstName();
Think of it this way if it helps
$author = $question->getAuthor();
echo $author->getFirstName();
Also note that you can't construct a Question with the string "Adam", you need to pass an instance of Author
$question = new Question('What is PHP', new Author('Adam', 'Lastname'));
You could create a new method:
class Question
{
// ...
function getAuthorFirstname()
{
return $this->author->getFirstname();
}
}
$question = new Question(.., new Author(..., ...));
echo $question->getAuthorFirstname();
Or, if you don't really care about Law of Demeter or feel that it doesn't apply:
$question = new Question(.., new Author(..., ...));
echo $question->getAuthor()->getFirstname();
In the end it all comes down to striking a balance between information hiding and pragmatism.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I ask your advise.
In my php file there are some classes.
class Template {
public $id;
public $title;
public $text;
public $description;
public $data = array();
public $content_html;
public $width_content = 500;
public $type;
public $time;
public $user;
public $category;
protected $CI;
// The next code works for a one element of array $data
function __construct($data = array()){
$this->title = $data['title'];
$this->text = $data['text'];
$this->category = $data['category'];
$this->type = $data['type'];
$this->time = $data['time'];
$this->CI =& get_instance();
$this->user = new InformationUser($data);
}
class Articles extends Template {
}
class News extends Template {
}
class Init {
public $posts = array('type' => 2);
}
The start point of my classes is a class Init.
Inside this class there is array of users posts.
In each element array there is a type value, which define what object class I must create.
For example:
class Init {
function define(){
foreach($this->posts as $val){
if($val['type'] == 2){
$article = new Articles($val);
//TODO $articles
} else if($val['type'] == 3){
$news = new News($val);
//TODO $news
}
}
}
}
I know that is variant is wrong, better to put all array posts() to class. But I can not do this.
I need, that for different type of element of array - to work separate class (for news - News class, article - class Article etc.)
What do you advise me?
From the minimal info provided.. I assume you are looking for something like this:
<?php
class Init {
public static function define($type, $text)
{
switch($type) {
case 1:
return new Articles($text);
break;
case 2:
return new News($text);
break;
default:
throw new Exception('Undefined type');
}
}
}
// $template = Init::define(1, 'article text');
// $template = Init::define(2, 'news text');