PHP combine $this variable - php

How to combine two variables to obtain / create new variable?
public $show_diary = 'my';
private my_diary(){
return 1;
}
public view_diary(){
return ${"this->"}.$this->show_diary.{"_diary()"}; // 1
return $this->.{"$this->show_diary"}._diary() // 2
}
both return nothing.

Your class should be like following:
class Test
{
public $show_diary;
function __construct()
{
$this->show_diary = "my";
}
private function my_diary(){
return 707;
}
public function view_diary(){
echo $this->{$this->show_diary."_diary"}(); // 707
}
}

It almost looks from your question like you are asking about how to turn simple variables into objects and then how to have one object contain another one. I could be way off, but I hope not:
So, first off, what is the differnce between an object and a simple variable? An object is really a collection of (generally) at least one property, which is sort of like a variable within it, and very often functions which do things to the properties of the object. Basically an object is like a complex variable.
In PHP, we need to first declare the strucutre of the object, this is done via a class statement, where we basicaly put the skeleton of what the object will be into place. This is done by the class statement. However, at this point, it hasn't actually been created, it is just like a plan for it when it is created later.
The creation is done via a command like:
$someVariable= new diary();
This executes so create a new variable, and lays it out with the structure, properties and functions defined in the class statement.
From then on, you can access various properties or call functions within it.
class show_diary
{
public $owner;
public function __construct()
{
$this->owner='My';
}
}
class view_diary
{
public $owner;
public $foo;
public function __construct()
{
$this->foo='bar';
$this->owner=new show_diary();
}
}
$diary= new view_diary();
print_r($diary);
The code gives us two classes. One of the classes has an instance of the other class within it.
I have used constructors, which are a special type of function that is executed each time we create a new instance of a class - basically each time we declare a variable of that type, the __construct function is called.
When the $diary= new view_diary(); code is called, it creates an instance of the view_diary class, and in doing so, the first thing it does is assigns it's own foo property to have the value 'bar' in it. Then, it sets it's owner property to be an instance of show_diary which in turn then kicks off the __construct function within the new instance. That in turn assigns the owner property of the child item to have the value 'My'.
If you want to access single properties of the object, you can do so by the following syntax:
echo $diary->foo;
To access a property of an object inside the object, you simply add more arrows:
echo $diary->owner->owner;

Like this?
$diary = $this->show_diary . '_diary';
return $this->$diary();

Related

Switch class results dynamically

I'm trying to write a code where I could run a function based on it's previous variables. I don't know how to explain any better but a sample will do. I'm trying to do something like this:
<?php
$agric = new Agriculture;
$newplant = $agric-> setClass('plant');
$newanimal = $agric->setClass('animal');
$agric->getAll(); // returns null
$newplant->setProperties($plant1_data); //uses plant
$newanimal->setProperties($animal1_data); // uses animal
$newplant->setProperties($plant2_data); //uses plant
$newanimal->setProperties($animal2_data); // uses animal
$newplant->getAll(); // returns all plants array
$newanimal->getAll(); // returns all animals array
$agric->getAll(); // returns both plants array and animals
?>
So, In one form, the new variables calls the setClass in order to work and everytime it is is called they use their setClass method to know which type of argument they should use to run their code. I know I could do this differently but I seem to love this approach. Any help will do. Thanks in advance
Thanks #everyone.. I finally got the answer to that. So the reason why I'm giving it to #Dragos is because phone factory seems to be the best approach to it. So, all I did was to create two classes. One is Agriculture which has a method to get the properties of what was called using "getAll()" and the Other is HandleAgric which also has "getAll()". The HandleAgric has its own setClass which is static and every time it is called, it instantiates a new Agriculture with its default parameter. So, Both Classes will have setClass() and getAll() as method. Something like this
<?php
class HandleAgric{
private static $Agriculture;
public function __construct(){
self::setClass();
}
function __call($method,$args){
$self = new self;
if(method_exists($self::$Agriculture, $method)){
$call = call_user_func(array($self::$Agriculture, $method));
return $call;
}
return trigger_error("Error Found!!! Aborting");
}
public static function setClass($class=null){
self::$Agriculture = new Agriculture;
$call = self::$Agriculture->setClass($class);
return $call;
}
}
//Example of usage
$Agric = new HandleAgric();
$Plant = $Agric::setClass("plant");
$Animal = $Agric::setClass("animal");
$Plant->setProperties($arrayList);
$Animal->setProperties($arrayList);
# $Plant->getAll() //return plants properties in array;
# $Animal->getAll() //return Animal properties in array;
# $Agric->getAll() //return Agric (both plant and animal) properties in array;
?>
I believe this to be much better.
For your example to work, the method setClass from Agriculture must work like a factory: it instantiates a class based on the parameter and returns the object.
Agriculture class must also keep all the objects instantiated inside setClass method in its own internal array, so when getAll method is called, it iterates through each object and executes their own getAll methods.

What is the difference in this way of method calling

As I got it, in the first example an object is created, and in the second one I don't see an object created. I am trying to understand, what is the difference between the two ways of method calling :
<?php
class Animal{
public $voice;
public function speak($sound){
echo $this->voice = $sound;
}
}
// Example 1
$tiger = new Animal();
$tiger->speak('Roar');
// Example 2
(new Animal)->speak("Cloak Cloak");
Whenever you use "new", you're creating an instance of an object (it can be temporary). The difference in your code is that in the first example, you're storing the instance in "$tiger", so it'll persist, but in the second example you're only instantiating a temporary object to call a method.
In the first example, you are assigning the variable $tiger as a new Object, by which you can then call the functions and variables associated with that object, by referencing $tiger.
i.e. as Tiger now equals an Object of Class Animal, it can speak.
However in the second example, you are still creating a new Object of class Animal, and as such it can speak - but you have not assigned it to a variable. So you cannot reference that same Object any longer.
So in the first example, if we wanted to name our $tiger, we could have the Class look something like this.
class Animal{
public $voice;
public $name = "I have no name.";
public function speak($sound){
echo $this->voice = $sound;
}
public function sayYourName(){
echo $this->name;
}
}
Now if we say,
$tiger = new Animal();
$tiger->speak('Roar');
$tiger->name = "Rory";
$tiger->sayYourName(); // This will echo "Rory"
However, if you try your second example instead :
(new Animal)->sayYourName(); // This will echo "I have no name."
So if you say :
(new Animal)->name = "Rory";
(new Animal)->sayYourName(); // This will still echo "I have no name".
This is because we haven't assigned a reference to the new animal, so while we can access methods of the function, and even predefined variables, we can't then reference them again later on.
To do that, we should stick to the first method (i.e. referencing)
$tiger = new Animal();
$tiger->name = "Rory";
$tiger->sayYourName();
In conclusion, use referencing to refer to an Object later on. i.e to get the animals attention, you have to call it by its name.

PHP - Private variable accessible through Class

I am working on a PHP class which looks like this:
<?php
class xyz{
public $car1;
public $car2;
private $owner;
public function __construct ($type){
$this->car1 = $type;
$this->owner = "John";
return $this->owner();
}
private function owner(){
return "Owner of ".$this->car1." is ".$this->owner;
}
Now, here's the problem when I call this class via other code, I can easily access private variable and the return function is not working correctly.
Here's the sample:
<?php
$car = new xyz("Sedan");
echo $car; //Expected result: Owner of Sedan is John.
?>
If I print $car, Here's what I get
Object ( [car1] => Sedan [car2] => "" [owner:xyz:private] => John )
How can I achieve my desired results and How can I protect private variable?
All the helps and suggestions will be appreciated.
Thanks!
Constructors are not supposed to return any value. The class constructor is supposed to initialize an object when creating a new instance (e.g. when you write $car = new xyz("sedan");, so anything you return goes nowhere. Create other methods in the class to return values.
If you want to echo the owner, make the owner method public and do `echo $car->owner();". The method returns a string, and then the string is echoed. Simple.
Echoing the object directly should result in an error in php 7, maybe you are running an older version of php that returns what you've seen, which is what happens if you call var_dump($car);. If you want to control how an object is converted into a string, you need to override the __toString method (see the php documentation).
Properties and methods visibility keywords are working fine, if you try to use $car->owner or $car->owner() without changing visibility you should see errors.

what happens when I create a object instance of my class

I have two class like this:
class one
{
public $var1 = 'anythig';
}
class two
{
public $var2 = 'anythig';
}
I want to know when I create a object instance of these classes what happens? My point is about the values stored in the memory. In reality I have some big class, and my resources are limited. then I want to know, If I put NULL into my class when don't need to it anymore is good ? and help to optimizing ?
I have a switch() to include the desired class. something like this:
switch{
case "one":
require_once('classes/one.php');
break;
case "two":
require_once('classes/two.php');
break;
}
Every time I only need one class. When I define a new object ($obj = new class) what happens to my class previously defined as object instance? that is remain in memory? and if I put NULL is helpful ? Please guide me ..
Edit:
The last line is useful or not ?
$obj = new myvlass;
echo $obj->property; // there is where that my class is done
$obj=NULL;
What determines when a class object is destroyed in PHP?
The PHP manual states that "the destructor method will be called as soon as all references to a particular object are removed" which is true (although can lead to some undesirable behaviour.)
It wouldn't really matter if you explicitly set an object variable to be NULL, PHP would destruct it anyway.
i would recommend my best way to implement class as follow :
<?php
class scSendMail
{
protected $from;
protected $toList;
protected $replyTo;
protected $subject;
protected $message;
public function __construct()
{
register_shutdown_function(array($this,'__destruct'));
$this->setFrom("updates#planetonnet.com");
$this->setReplyTo("noreply#planetonnet.com");
$this->setSubject("Update from PlanetOnNet.com");
}
public function __destruct()
{
unset($this->from);
unset($this->toList);
unset($this->replyTo);
unset($this->subject);
unset($this->message);
}
public function sendMail()
{
// ..... body
}
}
?>
in this way whenever object is not needed, it will destruct itself and free ups memory by unsetting variables used.
you can initiate another object anytime to replace with new object but be careful to use methods according to what object currently it is holding.
you can set to NULL to free ups memory whenever you dont need to use it anymore and use new variable to use new object.

Php Object oriented, Function calling

This is my php page persona.php:
<?php
class persona {
private $name;
public function __construct($n){
$this->name=$n;
}
public function getName(){
return $this->name;
}
public function changeName($utente1,$utente2){
$temp=$utente1->name;
$utente1->name=$utente2->name;
$utente2->name=$temp;
}
}
?>
The class persona is simple and just shows the constructor and a function that change two users name if called.
This is index.php:
<?php
require_once "persona.php" ;
$utente1 = new persona("Marcello");
print "First user: <b>". $utente1->getName()."</b><br><br>";
$utente2 = new persona("Sofia");
print "Second user: <b>". $utente2->getName()."</b><br>";
changename($utente1,$utente2);
print " Test after name changes: first user". $utente1->getName()."</b> second user". $utente2->getName();
?>
What I do not understand is how to call the changeName function from here.
I can understand where the confusion arises from...I think you are unsure if you should call changename on $utente1 or $utente2. Technically you can call it from either objects because they are both instances of Persona
But for clarity (and sanity), I would recommend converting the changeName function to a static function in its declaration:
public static function changeName($utente1,$utente2){
and then in your index.php you can call it as:
Persona::changename($utente1,$utente2);
From an architecture stamp point, this will help provide a better sense that the function is tied to the class of Persona, and objects can change swap names using that class function, as opposed to making it an instance function and then having any object execute it.
In your particular case you can call it as:
$utente1->changename($utente1,$utente2);
or
$utente2->changename($utente1,$utente2);
It doesn't matter which. As the method itself doesn't work with the classes properties (but only with the method parameters), you can call it from any object that exist.
But better (best practice, and better by design) is to develop a static method, as Raidenace already said, and call it like:
Persona::changename($utente1,$utente2);

Categories