I have a called class called ClientPolicy which is like this
class ClientPolicy {
var $serverHost="www.example.com";
var $httpPort = 80;
var $httpsPort = 443;
var $appKey;
var $secKey;
var $defaultContentCharset = "UTF-8";
}
and another class file name SyncAPIClient which looks like this
class SyncAPIClient{
function SyncAPIClient(ClientPolicy $clientPolicy) {
$this->clientPolicy = $clientPolicy;
}
function SyncAPIClient($appKey, $appSecret) {
$this->clientPolicy = new ClientPolicy();
$this->clientPolicy->appKey=$appKey;
$this->clientPolicy->secKey=$appSecret;
}
}
My questions are
1.) If you check the function in SyncAPIClient, you will notice that the ClientPolicy class was passed as a parameter before a variable, what does it really mean? What is the essence of passing a class in function parameter?
2.) I am getting an error "Cannot redeclare SyncAPIClient::SyncAPIClient()" in my script log and the reason is that SyncAPIClient function was called twice in SyncAPIClient class. How can I solve this issue? Is there any better way to write this SyncAPIClient function instead of passing it twice?
The author of this script is nowhere to be found and I am left to fix it.
1) Here the $clientPolicy variable that is passed to this function, needs be a ClientPolicy instance.
In this way, if the argument that is passed is different from an instance of ClientPolice class, an error is generated.
function SyncAPIClient(ClientPolicy $clientPolicy) {
$this->clientPolicy = $clientPolicy;
}
https://wiki.php.net/rfc/typed_properties_v2
https://laravel-news.com/php7-typed-properties
2) The error Cannot redeclare SyncAPIClient::SyncAPIClient() is caused because you are trying to declare two functions called SyncAPIClient ().
If in first SyncAPIClient() method you just want save the $clientPolicy in $this->clientPolicy, you can use the magic method __construct. Or just try changing the name of one of the functions, and the problem should be a problem.
class SyncAPIClient{
__construct(ClientPolicy $clientPolicy) {
$this->clientPolicy = $clientPolicy;
}
function SyncAPIClient($appKey, $appSecret) {
$this->clientPolicy = new ClientPolicy();
$this->clientPolicy->appKey=$appKey;
$this->clientPolicy->secKey=$appSecret;
}
}
https://www.php.net/manual/en/language.oop5.decon.php
http://www.zentut.com/php-tutorial/php-constructor-and-destructor/
Hope this helps!
I would've fix the code you have like this:
class SyncAPIClient
{
private $clientPolicy = null;
function SyncAPIClient(ClientPolicy $clientPolicy = null)
{
if($clientPolicy instanceof ClientPolicy){
$this->clientPolicy = $clientPolicy;
}else{
$this->clientPolicy = new ClientPolicy();
}
}
public function setAuthParams($appKey, $appSecret) {
$this->clientPolicy->appKey=$appKey;
$this->clientPolicy->secKey=$appSecret;
}
}
This way you can instantiate a SyncAPIClient with or without a ClientPolicy.
Without ClientPolicy:
$syncAPI = new SyncAPIClient();
$syncAPI->setAuthParams($apiKey, $apiSecret);
With ClientPolicy:
$clientPolicy = new ClientPolicy();
$clientPolicy->appKey=$appKey;
$clientPolicy->secKey=$appSecret;
$syncAPI = new SyncAPIClient($clientPolicy);
When using class and functions in combination like
Rtin::
Functions nested inside that class Rtin should have different names than that class name
So you shouldn't have function called rtin
However you can call function from outside the class with it's name
From the error you have may be due to:
function you nested in the class or the function outside the class has a duplicate outside the script itself. Like having function mentioned in included function.php file and also mentioned in the script itself so php get confused because function name is written in two php files at the same time
Example of class
class Rtin{
private $data;
private $results;
public function getResultsType(){
return ........
}
}
To call class use
$q = Rtin::getResultsType($data['name']);
In your example. Adapt it to the example I have provide and review the included files for duplicate function .
I wonder how i can call a method of a class inside of a method in other classes that called method is in a class that declared after the classes that use inside.
Let me show you an example:
Database.php:
class Database{
modifyUser($field,$change){
global $logging;
if($database->query('MYSQL QUERY')){
$logging->modifyUser($field,$change);
}
}
}
$database = new Database;
Logging.php:
class Logging{
modifyUser($field,$change){
global $database;
$database->query('Mysql Query for Logging');
}
}
$logging = new Logging;
now problem is if use top classes in included file like this:
user.php
include('database.php');
include('logging.php');
php shows an error that you use $logging variable which is not declared as class yet.
and if I change like this:
user.php
include('logging.php');
include('database.php');
same error but for $database; I don't know how to use it that PHP doesn't conflict for sequences.
I don't think it is possible, if you run the following code with command line you'll get "Segmentation fault" error;
class A
{
private $b;
public function __construct()
{
$b = new B();
}
}
class B
{
private $a;
public function __construct()
{
$a = new A();
}
}
$x = new A();
it is like an infinite loop.
First of all you can use include_once / require_once, so only the first time the file is needed, it will be loaded
Also, you can use autoloading
And instead of using global variables, either pass the instance or provide some sort of factory. Relying on global variables is bad for your encapsulation and it's ugly in an OO code
I've VERY NEW to PDO. I created the below function, but I read having the global database ($dbo) is a bad idea. The code works and outputs what I want it too. Any suggestions on how to improve/fix?
function langString($lang_id) {
global $dbo;
$lang_result=$dbo->prepare("SELECT lang_string FROM lang WHERE lang_id=:lang_id");
$lang_result->bindParam(":lang_id",$lang_id,PDO::PARAM_INT,3);
if($lang_result->execute()){
$lang_row = $lang_result->fetch(PDO::FETCH_OBJ);
echo "<br><br>$lang_row->lang_string";
}
}
echo langString(3);
Pass the variable as an argument to the function
function langString($lang_id, $dbo) {
$lang_result=$dbo->prepare("SELECT lang_string FROM lang WHERE lang_id=:lang_id");
$lang_result->bindParam(":lang_id",$lang_id,PDO::PARAM_INT,3);
if($lang_result->execute()){
$lang_row = $lang_result->fetch(PDO::FETCH_OBJ);
echo "<br><br>$lang_row->lang_string";
}
}
echo langString(3, $dbo);
The catch with the accepted answer is that you will end up trailing your database round every function as a parameter. This results in longer lists of parameters and as you get more stuff starts to look messy.
An alternative method is to make a Singleton which you can call to get the database connection e.g. Normally large projects will use this for more than just accessing the DB but here's a simple example
class DatabaseProvider {
private static $database;
private $dbo;
private function __construct() {
//Here's where you do your PDO connection creation
$this->dbo= new PDO()....;
}
public static function getDatabase() {
if(!isset(self::$database) {
self::$database = new DatabaseProvider();
}
return $database->dbo;
}
}
Then you just call DatabaseProvider::getInstance() which returns the pdo object
Use an include file...
Put your variables or even create a db object in the include, and then you can call it from anywhere.
function langString($lang_id) {
include($_SERVER['DOCUMENT_ROOT']."/dbconnect.php"); //Put your vars in this document
$lang_result=$dbo->prepare("SELECT lang_string FROM lang WHERE lang_id=:lang_id");
$lang_result->bindParam(":lang_id",$lang_id,PDO::PARAM_INT,3);
if($lang_result->execute()){
$lang_row = $lang_result->fetch(PDO::FETCH_OBJ);
echo "<br><br>$lang_row->lang_string";
}
}
echo langString(3);
If I create an object inside of the main scope:
INDEX.PHP:
$db = new database();
Then how can I use this same object inside of a completely different class?
ANYTHING.PHP:
class anything {
function __construct(){
$db->execute($something); # I want to use the same object from INDEX.PHP
}
}
Would I need to make $db a global or is there a 'better' more obvious way?
You could just use global to find it:
class anything {
function __construct(){
global $db;
$db->execute($something);
}
}
Or, you could pass it in when creating a new anything:
class anything {
function __construct($db) {
$db->execute($something);
}
}
It really depends on what makes the most sense for you.
For the DB you may want to use Singleton pattern
class anything
{
public function load($id)
{
$db = DB::getInstance();
$res = $db->query('SELECT ... FROM tablename WHERE id = '.(int)$id);
// etc...
}
}
You may want to extend it if you need different DB connections at the same time (i.e main db and forum's db). Then you'll use it like DB::getInstance('forum'); and store instances in associative array.
You could pass it as an argument, like this
function __construct($db){
$db->execute($something);
}
then when you instance anything, do it as anything($db)
As Paolo and ONi suggested you can define $db as global inside the method or pass it into the constructor of the class. Passing it in will create a reference to that object so it will in fact be the same $db object. You could also use the $GLOBALS array and reference $db that way.
$GLOBALS["db"];
I'm assuming that index.php and anything.php are linked together somehow by include() or require() or some similar method?
In Paolo's post:
After you pass it, you can then assign it to a class variable like this:
class anything {
var $db_obj;
function __construct($db) {
$this->db_obj = $db;
}
function getUsers() {
return $this->db_obj->execute($something);
}
}
I have been noticing __construct a lot with classes. I did a little reading and surfing the web, but I couldn't find an explanation I could understand. I am just beginning with OOP.
I was wondering if someone could give me a general idea of what it is, and then a simple example of how it is used with PHP?
__construct was introduced in PHP5 and it is the right way to define your, well, constructors (in PHP4 you used the name of the class for a constructor).
You are not required to define a constructor in your class, but if you wish to pass any parameters on object construction then you need one.
An example could go like this:
class Database {
protected $userName;
protected $password;
protected $dbName;
public function __construct ( $UserName, $Password, $DbName ) {
$this->userName = $UserName;
$this->password = $Password;
$this->dbName = $DbName;
}
}
// and you would use this as:
$db = new Database ( 'user_name', 'password', 'database_name' );
Everything else is explained in the PHP manual: click here
__construct() is the method name for the constructor. The constructor is called on an object after it has been created, and is a good place to put initialisation code, etc.
class Person {
public function __construct() {
// Code called for each new Person we create
}
}
$person = new Person();
A constructor can accept parameters in the normal manner, which are passed when the object is created, e.g.
class Person {
public $name = '';
public function __construct( $name ) {
$this->name = $name;
}
}
$person = new Person( "Joe" );
echo $person->name;
Unlike some other languages (e.g. Java), PHP doesn't support overloading the constructor (that is, having multiple constructors which accept different parameters). You can achieve this effect using static methods.
Note: I retrieved this from the log of the (at time of this writing) accepted answer.
It's to declare the constructor.
class Cat
{
function __construct()
{
echo 'meow';
}
}
Constructors are invoked whenever a new instance of the class is created, in this case, the constructor will be invoked with this line:
$cat = new Cat();
In older PHP versions, the constructor could also be declared using the class name, for ex:
class Cat
{
function Cat()
{
echo 'meow';
}
}
I think this is important to the understanding of the purpose of the constructor.
Even after reading the responses here it took me a few minutes to realise and here is the reason.
I have gotten into a habit of explicitly coding everything that is initiated or occurs. In other words this would be my cat class and how I would call it.
class_cat.php
class cat {
function speak() {
return "meow";
}
}
somepage.php
include('class_cat.php');
mycat = new cat;
$speak = cat->speak();
echo $speak;
Where in #Logan Serman's given "class cat" examples it is assumed that every time you create a new object of class "cat" you want the cat to "meow" rather than waiting for you to call the function to make it meow.
In this way my mind was thinking explicitly where the constructor method uses implicity and this made it hard to understand at first.
The constructor is a method which is automatically called on class instantiation. Which means the contents of a constructor are processed without separate method calls. The contents of a the class keyword parenthesis are passed to the constructor method.
The __construct method is used to pass in parameters when you first create an object--this is called 'defining a constructor method', and is a common thing to do.
However, constructors are optional--so if you don't want to pass any parameters at object construction time, you don't need it.
So:
// Create a new class, and include a __construct method
class Task {
public $title;
public $description;
public function __construct($title, $description){
$this->title = $title;
$this->description = $description;
}
}
// Create a new object, passing in a $title and $description
$task = new Task('Learn OOP','This is a description');
// Try it and see
var_dump($task->title, $task->description);
For more details on what a constructor is, see the manual.
I Hope this Help:
<?php
// The code below creates the class
class Person {
// Creating some properties (variables tied to an object)
public $isAlive = true;
public $firstname;
public $lastname;
public $age;
// Assigning the values
public function __construct($firstname, $lastname, $age) {
$this->firstname = $firstname;
$this->lastname = $lastname;
$this->age = $age;
}
// Creating a method (function tied to an object)
public function greet() {
return "Hello, my name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)";
}
}
// Creating a new person called "boring 12345", who is 12345 years old ;-)
$me = new Person('boring', '12345', 12345);
// Printing out, what the greet method returns
echo $me->greet();
?>
For More Information You need to Go to codecademy.com
class Person{
private $fname;
private $lname;
public function __construct($fname,$lname){
$this->fname = $fname;
$this->lname = $lname;
}
}
$objPerson1 = new Person('john','smith');
__construct is always called when creating new objects or they are invoked when initialization takes place.it is suitable for any initialization that the object may need before it is used. __construct method is the first method executed in class.
class Test
{
function __construct($value1,$value2)
{
echo "Inside Construct";
echo $this->value1;
echo $this->value2;
}
}
//
$testObject = new Test('abc','123');
I believe that function __construct () {...} is a piece of code that can be reused again and again in substitution for TheActualFunctionName () {...}.
If you change the CLASS Name you do not have to change within the code because the generic __construct refers always to the actual class name...whatever it is.
You code less...or?
__construct is a method for initializing of new object before it is used.
http://php.net/manual/en/language.oop5.decon.php#object.construct
Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).
__construct simply initiates a class. Suppose you have the following code;
Class Person {
function __construct() {
echo 'Hello';
}
}
$person = new Person();
//the result 'Hello' will be shown.
We did not create another function to echo the word 'Hello'. It simply shows that the keyword __construct is quite useful in initiating a class or an object.
A constructor allows you to initialize an object's properties upon creation of the object.
If you create a __construct() function, PHP will automatically call this function when you create an object from a class.
https://www.w3schools.com/php/php_oop_constructor.asp
Let me explain __construct() without first using the method ... One thing to know about __construct() is that it is an inbuilt function, well let me call it method in PHP. Just as we have print_r() for procedural, the __construct() is an inbuilt for OOP.
That being said, let's explore why you should use this function called __construct().
/*=======Class without __construct()========*/
class ThaddLawItSolution
{
public $description;
public $url;
public $ourServices;
/*===Let us initialize a value to our property via the method set_name()==== */
public function setName($anything,$anythingYouChoose,$anythingAgainYouChoose)
{
$this->description=$anything;
$this->url=$anythingYouChoose;
$this->ourServices=$anythingAgainYouChoose;
}
/*===Let us now display it on our browser peacefully without stress===*/
public function displayOnBrowser()
{
echo "$this->description is a technological company in Nigeria and our domain name is actually $this->url.Please contact us today for our services:$this->ourServices";
}
}
//Creating an object of the class ThaddLawItSolution
$project=new ThaddLawItSolution;
//=======Assigning Values to those properties via the method created====//
$project->setName("Thaddlaw IT Solution", "https://www.thaddlaw.com", "Please view our website");
//===========Let us now display it on the browser=======
$project->displayOnBrowser();
__construct() makes life for you very easy, imaging the time it took me to assigning values to those properties via that method. From the code above, I created an object which is first and then assign values to the properties which is second before finally showing it on the browser. But using __construct() while creating an object i.e. $project= new ThaddLawItSolution; you would do what you did for assigning values to that method immediately while creating the object, i.e.
$project=new ThaddLawItSolution("Thaddlaw IT Solution", "https://www.thaddlaw.com","Please view our website");
//===Let's now use __constructor=====
Just remove that method called setName and put __construct(); and when creating an object, you assign the values at once. That is the point behind the whole __construct() method. But note that this is an inbuilt method or function