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);
Related
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.
On my site at the beginning of every script I include a "bootstrap" script which queries a few things from the database, does some calculations and then loads the variables into constants that I define one by one.
Some examples are:
define("SITE_ID", $site_id); // $site_id is pulled from a field in the database
define("SITE_NAME", $site_name);
// pulled from a field in the same row as the above
define("STOCK_IDS", $stock_ids);
//computed array of stock id integers from a different query.
//I perform logic on the array after the query before putting it in the definition
define("ANALYTICS_ENABLED", false);
// this is something I define myself and isnt "pulled" from a database
Now, I have many functions on the site. One example function is get_stock_info. And it references the STOCK_IDS constant.
What I want to do is have a class which has the above constants in it and the get_stock_info function.
Would the best approach to be have an empty class "site", create an instance of it and then afterwards define the static variables above one by one? Or is that not a good way and should I move all of of my logic which pulls from the database and calculates SITE_ID, STOCK_IDS, ANALYTICS_ENABLED etc into the constructor instead?
Ultimately I want the class to contain all of the above info and then I would be able to use class methods such as site::get_stock_info() and those methods will have access to the constants via self:: or this.
There's a lot more I want to do than that but that would give me enough to figure the rest out.
I think this approach isn't the best. You should consider not using constants as your values aren't constant. For your case it is better to have a class with classic getters methods.
Something like this:
class SiteInfo
{
private $siteId;
private $siteName;
private $stockIds;
private $analyticsEnabled;
public function __construct()
{
// Results from the database
$results = $query->execute();
$this->siteId = $results['siteId'];
$this->siteName = $results['siteName'];
$this->stockIds = $results['stockIds'];
$this->analyticsEnabled = $results['analyticsEnabled'];
}
public function getSiteId()
{
return $this->siteId;
}
public function getSiteName()
{
return $this->siteName;
}
public function getStockIds()
{
return $this->stockIds;
}
public function isAnalyticsEnabled()
{
return $this->analyticsEnabled;
}
}
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.
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();
$this->a->b->c->d calling methods from a superclass in php
Ive asked a question on this link I ve problem with this tecnique I am able to call the sub classes from a class
like this
$chesterx->db->query();
I wanna do get another class from sub class
for example
i want to query execute which was come from the sql class
ROOT
|
sql <--- chesterx ---> db
i wanna use the sql class from db
the problem i cant return the chesterx class from db class
/edit/
I have some classes like news, members, categories, db and query
and i did it like the link which was on the subject top
public function __construct(){
function __construct(){
if(!$this->db){
include(ROOT."/func/class/bp.db.class.php");
$this->db = new db;
}
if(!$this->chester){
include(ROOT."/func/class/bp.chester.class.php");
$this->db = new chester;
}
}
i called the db class with this code and now i am able to call and use the db class methods well
for example
i want to use a method from db
that method is containing a value which was returning a data from the chester class's method
i wish i were clarify myself
/edit/
is there anyway to do this?
I find Ionut G. Stan's solution good for your case, but you might also want to consider the factory/singleton pattern, though it's only good if your chesterx class is a global one, and only called once
The below snippet might be a solution, although I don't really like the circular reference. Try it and use it as you see fit. And by the way, what you are calling class and subclass are actually containing and contained class.
class Database
{
public $chesterx;
public function __construct($chesterx)
{
$this->chesterx = $chesterx;
}
}
class Sql
{
public $chesterx;
public function __construct($chesterx)
{
$this->chesterx = $chesterx;
}
}
class Chesterx
{
public $db;
public $sql;
public function __construct()
{
$this->db = new Database($this);
$this->sql = new Sql($this);
}
}